package com.central.apps.handler.purchase;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.common.constant.AppConstant;
import com.central.app.common.util.DateUtils;
import com.central.app.service.HandlerService;
import com.central.apps.common.util.DateUtiles;
import com.central.apps.entity.BlMessage;
import com.central.apps.service.MessageService;
import com.central.apps.util.StringUtil;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.exception.service.ServiceException;
import com.central.common.util.ToolUtil;
import com.central.common.web.PageResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.cert.dane.DANECertificateFetcher;
import org.bouncycastle.crypto.tls.MACAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.lang.Math.abs;
import static java.lang.Math.copySign;
import static org.bouncycastle.asn1.x500.style.RFC4519Style.o;

/**
 * 采购接收处理类
 *
 * @author 李大超
 * @date 2022/9/1
 */
@Component
@Slf4j
public class PurchaseReceiptHandler extends BaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private MessageService messageService;

    @Override
    public String validateSave(String app, String objName, Map<String, Object> data) throws Exception {
        System.out.println("===> enter PurchaseReceiptHandler validateSave");
        System.out.println("===> data: " + data);
        System.out.println("===> objName: " + objName);
        System.out.println("===> app: " + app);
        if ("gq_prtdetailline".equals(objName)) {
            // TODO 校验是否大于
        }
        return null;
    }

    @Override
    public String validateDelete(String app, String objName, Long id) throws Exception {
        System.out.println("===> enter PurchaseReceiptHandler validateDelete");
        System.out.println("===> id: " + id);
        System.out.println("===> objName: " + objName);
        System.out.println("===> app: " + app);
        if ("gq_prtsummaryline".equals(objName)) {
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_prtsummaryline t where t.id = " + id + "");
            if (CollectionUtils.isNotEmpty(list)) {
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prtsummaryline where id=" + id);
                if (CollectionUtils.isNotEmpty(bySql)) {
                    for (int i = 0; i < bySql.size(); i++) {
                        Map<String, Object> map = bySql.get(i);
                        String prtid = MapUtils.getString(map, "prtid");
                        String ppslid = MapUtils.getString(map, "ppslid");
                        List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_prtdetailline where prtid ='" + prtid + "' and ppslid ='" + ppslid + "'");
                        if (CollectionUtils.isNotEmpty(bySql1)) {
                            for (int j = 0; j < bySql1.size(); j++) {
                                Map<String, Object> map1 = bySql1.get(j);
                                String id1 = MapUtils.getString(map1, "id");
                                List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_puracceptline where prtsummarylineid='" + id1 + "'");
                                if (CollectionUtils.isNotEmpty(bySql2)) {
                                    return "接收行已经生成验收单，不允许删除!";
                                }
                            }
                        }

                    }

                }
            }
        } else if ("gq_prtdetailline".equals(objName)) {
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_puracceptline where prtsummarylineid=" + id);
            if (CollectionUtils.isNotEmpty(bySql)) {
                return "接收行已经生成验收单，不允许删除!";
            }

        }else if ("gq_purchasereceipt".equals(objName)){
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_purchasereceipt where id='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                //获取接收编号
                String receiptnum = MapUtils.getString(bySql.get(0), "receiptnum");
                //查询验收单是否存在该接收
                List<Map<String, Object>> select = handlerService.findBySql("select receiptnum from gq_puraccept where receiptnum='"+receiptnum+"'");
                if(CollectionUtils.isNotEmpty(select)){
                    return "接收行已经生成验收单，不允许删除!";
                }
            }
        }
        return super.validateDelete(app, objName, id);
    }
    @Override
    public void beforDelete(String app, String objName, Long id, boolean isLogic) {
        System.out.println("===> enter PurchaseReceiptHandler beforDelete");
        System.out.println("===> id: " + id);
        System.out.println("===> objName: " + objName);
        System.out.println("===> app: " + app);
        if ("gq_purchasereceipt".equals(objName)) {
            // 删除采购接收汇总行信息
            handlerService.updateBySql("delete from gq_prtsummaryline where prtid = " + id);
            // 删除采购接收明细行信息
            handlerService.updateBySql("delete from gq_prtdetailline where prtid = " + id);
        } else if ("gq_prtsummaryline".equals(objName)) {
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_prtsummaryline t where t.id != " + id + " and t.prtid = (select prtid from gq_prtsummaryline where id = " + id + ")");

            if (CollectionUtils.isEmpty(list)) {
                // 修改采购申请是否存在子表数据测试
                handlerService.updateBySql("update gq_purchasereceipt set haschild = 0 where haschild = 1 and id = (select prtid from gq_prtsummaryline where id = " + id + ")");
            }
        }
    }

    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        System.out.println("===> enter PurchaseReceiptHandler validateSave");
        System.out.println("===> params: " + params);
        System.out.println("===> type: " + type);
        System.out.println("===> app: " + app);
        if ("purchasere".equals(type)){
            List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT * from biz_attribute where object_id ='970'");
            String columnname="";
            String string="";
            String ponum = MapUtils.getString(params, "ponum");
            String poid = MapUtils.getString(params, "poid");
            String prtid = MapUtils.getString(params, "prtid");
            if (CollectionUtils.isNotEmpty(bySql1)){
                for (int i=0;i<bySql1.size();i++){
                    Map<String, Object> map = bySql1.get(i);
                    columnname = MapUtils.getString(map, "columnname");
                    //字段名_orders: "asc"
                    String columnname1= columnname+"_orders";
                    String columnname11 = MapUtils.getString(params, columnname1);

                    if (StringUtils.isNotEmpty(columnname11)) {
                        string  = "order by "+columnname+" "+columnname11;
                    }
                }
            }
            String itemnum = MapUtils.getString(params, "itemnum");
            String itemdesc = MapUtils.getString(params, "itemdesc");
            String commerceorder = MapUtils.getString(params, "commerceorder");
            String billtoattn = MapUtils.getString(params, "billtoattn");
            String suppliername = MapUtils.getString(params, "suppliername");
            String ponum1 = MapUtils.getString(params, "ponum");
            ArrayList<String> strings = new ArrayList<>();
            strings.add(itemnum);
            strings.add("itemnum");
            strings.add(itemdesc);
            strings.add("itemdesc");
            strings.add(commerceorder);
            strings.add("commerceorder");
            strings.add(billtoattn);
            strings.add("billtoattn");
            strings.add(suppliername);
            strings.add("suppliername");
            strings.add(ponum1);
            strings.add("ponum");
            List<Map<String, Object>> bySql=null;
            if (StringUtils.isNotEmpty(ponum)){
                if (StringUtils.isEmpty(string)){
                    string ="order by t.createtime desc";
                }
                if(itemnum==null&&itemdesc==null&&commerceorder==null&&billtoattn==null&&suppliername==null&&ponum1==null){
                    bySql = handlerService.findBySql("select t.* from gq_posline t where t.poid='" + poid + "'  and  t.unreceivedqty>0 and t.qualquantity>0 and (t.shutreason IS null or t.shutreason = '') and t.id not in (select poslid from gq_prtsummaryline where prtid = '" + prtid + "') and t.ponum ='" + ponum + "' and t.poid in (select id from gq_po where status ='已批准') "+string+"");
                }else {
                    String list = " t.";
                    String list1=" like";
                    String list3="";
                    //String list2="and";
                    for (int i=0;i<strings.size();i=i+2){
                        String s = strings.get(i);
                        if (s!=null){
                            if(list3==""){
                                list3=list3+list+strings.get(i+1)+list1+"'%"+s+"%'";
                            }else{
                                list3=list3+" and "+list+strings.get(i+1)+list1+"'%"+s+"%'";
                            }
                        }
                    }
                    bySql = handlerService.findBySql("select t.* from gq_posline t where "+list3+" and t.poid='" + poid + "'  and  t.unreceivedqty>0 and (t.shutreason IS null or t.shutreason = '') and t.qualquantity>0 and t.id not in (select poslid from gq_prtsummaryline where prtid = '" + prtid + "') and t.ponum ='" + ponum + "' and t.poid in (select id from gq_po where status ='已批准') "+string+"");
                }
            }else {
                if (StringUtils.isEmpty(string)){
                    string ="order by t.createtime desc";
                }
                if (itemnum==null&&itemdesc==null&&commerceorder==null&&billtoattn==null&&suppliername==null&&ponum1==null){
                    bySql = handlerService.findBySql("select t.* from gq_posline t where  t.unreceivedqty>0 and t.qualquantity>0 and (t.shutreason IS null or t.shutreason = '') and t.id not in (select poslid from gq_prtsummaryline where prtid = '" + prtid + "')  and t.poid in (select id from gq_po where status ='已批准') "+string+"");
                }else {
                    String list = " t.";
                    String list1=" like";
                    String list3="";
                    //String list2="and";
                    for (int i=0;i<strings.size();i=i+2){
                        String s = strings.get(i);
                        if (s!=null){
                            if(list3==""){
                                list3=list3+list+strings.get(i+1)+list1+"'%"+s+"%'";
                            }else{
                                list3=list3+" and "+list+strings.get(i+1)+list1+"'%"+s+"%'";
                            }
                        }
                    }
                    bySql = handlerService.findBySql("select t.* from gq_posline t where "+list3+" and  t.unreceivedqty>0 and t.qualquantity>0 and (t.shutreason IS null or t.shutreason = '') and t.id not in (select poslid from gq_prtsummaryline where prtid = '" + prtid + "')  and t.poid in (select id from gq_po where status ='已批准') "+string+"");
                }

            }
            if (CollectionUtils.isNotEmpty(bySql)) {
                int page = 1;
                int limit = 10;
                if (MapUtils.getInteger(params, AppConstant.BIZ_QUERY_PAGE) != null && MapUtils.getInteger(params, AppConstant.BIZ_QUERY_LIMIT) != null) {
                    page = MapUtil.getInt(params, AppConstant.BIZ_QUERY_PAGE);
                    limit = MapUtil.getInt(params, AppConstant.BIZ_QUERY_LIMIT);
                }

                List<Map<String, Object>> collect = bySql.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
                return PageResult.<Map<String, Object>>builder().data(collect).code(0).count((long) bySql.size()).build();
            }
        }
        return super.operate(app, type, params);
    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        System.out.println("===> enter PurchaseReceiptHandler validateSave");
        if ("gq_prtdetailline".equals(objName)){
            String id = MapUtils.getString(data, "id");
            Float arrquantity = MapUtils.getFloat(data, "arrquantity");//到货数量
            Float qualiquan = MapUtils.getFloat(data, "qualiquan");//合格数量
            List<Map<String, Object>> bySql = handlerService.findBySql("select unreceivedqty from gq_prtdetailline where id='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                Map<String, Object> map = bySql.get(0);
                Float unreceivedqty = MapUtils.getFloat(map, "unreceivedqty");
                if (arrquantity.compareTo(unreceivedqty)>0){
                    throw  new ServiceException("到货数量不能大于未接收数量！");
                }else if (qualiquan.compareTo(unreceivedqty)>0){
                    throw  new ServiceException("合格数量不能大于未接收数量！");
                }
            }
        }
        super.beforSave(app, objName, data, isUpdate);
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        System.out.println("===> enter PurchaseReceiptHandler afterSave");
        System.out.println("===> app: " + app);
        System.out.println("===> objName: " + objName);
        System.out.println("===> data: " + data);
        System.out.println("===> isUpdate: " + isUpdate);
        if ("gq_prtsummaryline".equals(objName)) {//订单汇总行
            Integer prtid = MapUtils.getInteger(data, "prtid");

            // 查询采购接收主信息
            List<Map<String, Object>> prtList = handlerService.findBySql("select type from gq_purchasereceipt where id = " + prtid);//主表
            Map<String, Object> prtMap = prtList.get(0);
            String type = MapUtils.getString(prtMap, "type");
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select ponum from gq_prtsummaryline where prtid=" + prtid);
            if (CollectionUtils.isNotEmpty(bySql1)){
                String ponum = MapUtils.getString(bySql1.get(0), "ponum");
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_po where ponum='" + ponum + "'");
                if (CollectionUtils.isNotEmpty(bySql)) {
                    String description = MapUtils.getString(bySql.get(0), "description");
                    String billtoattn = MapUtils.getString(bySql.get(0), "billtoattn");
                    handlerService.updateBySql("update gq_purchasereceipt set ponum='"+ponum+"',podesc='"+description+"',recipient='"+billtoattn+"' where id = " + prtid);
                    //receiptdesc='"+description+"',
                }
            }

            if ("接收".equals(type)) {
                if (isUpdate == true) {
                    Integer ppslid = MapUtils.getInteger(data, "ppslid");
                    String poslid = MapUtils.getString(data, "poslid");
                    //采购订单子表
                    List<Map<String, Object>> bySql = handlerService.findBySql("SELECT * from gq_posline where id ='" + poslid + "'");
                    if (CollectionUtils.isNotEmpty(bySql)) {
                        String prnum = MapUtils.getString(bySql.get(0), "prnum");

                    }
                    // 查询采购接收明细行信息
                    List<Map<String, Object>> prtdlList = handlerService.findBySql("select id from gq_prtdetailline where ppslid = " + ppslid);

                    for (Map<String, Object> prtdlMap : prtdlList) {
                        Map<String, Object> prtdlUpdMap = new HashMap<>();
                        prtdlUpdMap.put("id", prtdlMap.get("id"));
                        //prtdlUpdMap.put("warehousenum", data.get("warehousenum"));
                        //prtdlUpdMap.put("binnum", data.get("binnum"));
                        //prtdlUpdMap.put("batchnum", data.get("batchnum"));
                        prtdlUpdMap.put("unit", data.get("unit"));
                        //prtdlUpdMap.put("whepasaccep", data.get("whepasaccep"));
                        prtdlUpdMap.put("expirydate", data.get("expirydate"));
                        prtdlUpdMap.put("productiondate", data.get("productiondate"));
                        prtdlUpdMap.put("receivetolerance", data.get("receivetolerance"));
                        prtdlUpdMap.put("returnreason", data.get("returnreason"));
                        prtdlUpdMap.put("convertfactor", data.get("convertfactor"));
                        handlerService.update("gq_prtdetailline", prtdlUpdMap);
                    }
                } else {
                    // 组织插入采购接收明细行信息
                    combinePrtDetail(data);
                }
            } else if ("退/换".equals(type)) {
                // 组织插入采购接收退换明细行信息
                combinePrtReturnDetail(data);
            }

            // 更新采购接收主表是否存在子表数据
            handlerService.updateBySql("update gq_purchasereceipt set haschild = 1 where (haschild = 0 or haschild is null) and id = " + prtid);
        } else if ("gq_purchasereceipt".equals(objName)) {
            Integer prtid = MapUtils.getInteger(data, "id");
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_prtdetailline where prtid='" + prtid + "'");
            if (CollectionUtils.isNotEmpty(bySql1)){
                for (int i=0;i<bySql1.size();i++){
                    Map<String, Object> map = bySql1.get(i);
                    String acceptments = MapUtils.getString(map, "acceptments");
                    if (StringUtils.isNotEmpty(acceptments)){
                        if (acceptments.contains("02")||acceptments.contains("03")||acceptments.contains("05")){
                            String the="是";
                            handlerService.updateBySql("update gq_purchasereceipt set whether='"+the+"' where id='"+prtid+"'");
                        }else {
                            String the="否";
                            handlerService.updateBySql("update gq_purchasereceipt set whether='"+the+"' where id='"+prtid+"'");
                        }
                    }

                }
            }
            //主表保存，去变更汇总行里面的合格数量/抽检数量
            updatePrtsummaryLine(prtid);
            // 修改采购申请是否存在子表数据
            handlerService.updateBySql("update gq_purchasereceipt set haschild = 0 where haschild is null and id = " + prtid);
//            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prtsummaryline where prtid=" + prtid);
//            if (CollectionUtils.isNotEmpty(bySql)){
//                for (int i=0;i<bySql.size();i++){
//                    Map<String, Object> map = bySql.get(i);
//                    String prtid1 = MapUtils.getString(map, "prtid");
//                    String ppslid = MapUtils.getString(map, "ppslid");
//                    float receiveqty1=0;
//                    float qualiquan1=0;
//                    float sampquan1=0;
//                    String prtid2=null;
//                    String ppslid2=null;
//                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_prtdetailline where prtid='" + prtid1 + "' and ppslid='" + ppslid + "'");
//                    if (CollectionUtils.isNotEmpty(bySql1)){
//                        for (int j=0;j<bySql1.size();j++){
//                            Map<String, Object> map1 = bySql1.get(j);
//                            prtid2= MapUtils.getString(map1, "prtid");
//                            ppslid2= MapUtils.getString(map1, "ppslid");
//                            Float receiveqty = MapUtils.getFloat(map1, "receiveqty");//入库数量
//                            Float qualiquan = MapUtils.getFloat(map1, "qualiquan");//合格数量
//                            Float sampquan = MapUtils.getFloat(map1, "sampquan");//抽检数量
//                            String insresults = MapUtils.getString(map1, "insresults");//检验结果
//                            receiveqty1=receiveqty1+receiveqty;
//                            qualiquan1=qualiquan1+qualiquan;
//                            sampquan1=sampquan1+sampquan;
//
//                        }
//                        handlerService.updateBySql("update gq_prtsummaryline set qualiquan ="+qualiquan1+",receiveqty="+receiveqty1+",sampquan="+sampquan1+" where prtid='"+prtid2+"' and ppslid='"+ppslid2+"'");
//                    }
//                }
//            }

        } else if ("gq_prtdetailline".equals(objName)) {

            //汇总采购接收行数据
            Integer id = MapUtils.getInteger(data, "id");
            String prtid1 = MapUtils.getString(data, "prtid");
            String ppslid1 = MapUtils.getString(data, "ppslid");
            String prtslid = MapUtils.getString(data,"prtslid");
            //原查询逻辑
           // List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prtdetailline where prtid='" + prtid1 + "' and ppslid='" + ppslid1 + "'");
            //新查询逻辑
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prtdetailline where prtid='" + prtid1 + "' and prtslid='" + prtslid + "'");

            if (CollectionUtils.isNotEmpty(bySql)) {
//                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_prtsummaryline where prtid='" + prtid1 + "' and ppslid='" + ppslid1 + "'");
                float receiveqty1 = 0;//入库数统计
                float qualiquan1 = 0;
                float sampquan1 = 0;
                float returnqty1 = 0;//退货数统计
                float arrquantity1 = 0;
//                Map<String, Object> map1 = bySql1.get(0);
//                Float receivedqty = MapUtils.getFloat(map1, "receivedqty");//已接收数量
//                Float unreceivedqty = MapUtils.getFloat(map1, "unreceivedqty");//未接收数量
                for (int i = 0; i < bySql.size(); i++) {
                    Map<String, Object> map = bySql.get(i);
                    //获取检验结果，如果是退换货，需要汇总退换货数量
                    String id1 = MapUtils.getString(map, "id");
                    Float receiveqty = MapUtils.getFloat(map, "receiveqty");//接收数量
                    Float qualiquan = MapUtils.getFloat(map, "qualiquan");//合格数量
                    Float sampquan = MapUtils.getFloat(map, "sampquan");//抽检数量
                    String insresults = MapUtils.getString(map, "insresults");//检验结果
                    Float arrquantity = MapUtils.getFloat(map, "arrquantity");//到货数量
                    Float orderqty = MapUtils.getFloat(map, "orderqty");//采购数量
                    if ("退货".equals(insresults)||"换货".equals(insresults)) {
                        //returnqty1 = returnqty1 + arrquantity;//检验结果不合格，统计退换数量
                        returnqty1 = returnqty1 + arrquantity;
                        handlerService.updateBySql("update gq_prtdetailline set returnqty="+arrquantity+" where id='"+id1+"'");
                    } else if ("合格".equals(insresults)) {
                        receiveqty1 = receiveqty1 + receiveqty;//检验结果合格，统计入库数量
                        qualiquan1 = qualiquan1 + qualiquan;//统计合格数量
                        handlerService.updateBySql("update gq_prtdetailline set returnqty="+0+" where id='"+id1+"'");
//                        receivedqty = receivedqty + qualiquan;
//                        unreceivedqty = unreceivedqty - receivedqty;

                    }
                    arrquantity1 = arrquantity1 + arrquantity;
                    sampquan1 = sampquan1 + sampquan;
                }
                //receiveqty="+receiveqty1+",入库数量
                //旧更新逻辑
               // handlerService.updateBySql("update gq_prtsummaryline set qualiquan =" + qualiquan1 + ",sampquan=" + sampquan1 + ",returnqty=" + returnqty1 + ",number=" + receiveqty1 + ",qualquantity="+arrquantity1+" where prtid='" + prtid1 + "' and ppslid='" + ppslid1 + "'");
                //新逻辑
                handlerService.updateBySql("update gq_prtsummaryline set qualiquan =" + qualiquan1 + ",sampquan=" + sampquan1 + ",returnqty=" + returnqty1 + ",number=" + receiveqty1 + ",qualquantity="+arrquantity1+" where prtid='" + prtid1 + "' and id='" + prtslid + "'");

                //                List<Map<String, Object>> bySql1 = handlerService.findBySql("select qualquantity from gq_prtsummaryline where prtid='" + prtid1 + "' and ppslid ='" + ppslid1 + "'");
//                if (CollectionUtils.isNotEmpty(bySql1)){
//                    Map<String, Object> map = bySql1.get(0);
//                    Float qualquantity = MapUtils.getFloat(map, "qualquantity");
//                    if (qualquantity.compareTo(arrquantity1)==0){
//
//                    }else {
//                        throw new ServiceException("采购接收行到货数量和不等于会总行到货数量请查看！");
//                    }
//                }
            }
            if ("gq_prtdetailline".equals(objName) && isUpdate) {
                int pid = MapUtils.getIntValue(data, "id");
                List<Map<String, Object>> list = handlerService.findBySql("select acceptments from gq_prtdetailline where id = " + pid);
                if (CollectionUtils.isNotEmpty(list)) {
                    String acceptments = MapUtils.getString(list.get(0), "acceptments");
                    if (StringUtils.isEmpty(acceptments)){
                        int acceptment=0;
                        handlerService.updateBySql("update gq_prtdetailline set acceptments="+acceptment+" where id = " + pid);
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", pid);
                        map.put("acceptmentsnew"," ");
                        handlerService.update("gq_prtdetailline", map);
                    }else if(acceptments.equals("0")){
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", pid);
                        map.put("acceptmentsnew"," ");
                        handlerService.update("gq_prtdetailline", map);

                    }else{
                        String acceptmentsnew = StringUtil.setString(acceptments);
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", pid);
                        map.put("acceptmentsnew", acceptmentsnew);
                        handlerService.update("gq_prtdetailline", map);
                    }

                }
            }
        }

    }

    public void updatePrtsummaryLine(Integer prtid1){
        List<Map<String, Object>> bySql1 = handlerService.findBySql("select ppslid,id from gq_prtsummaryline where prtid = " + prtid1 + "");
        if (CollectionUtils.isNotEmpty(bySql1)) {
            for (Map<String, Object> map : bySql1) {
                String ppslid1 = MapUtils.getString(map, "ppslid");
                String prtslid = MapUtils.getString(map, "id");

                //原逻辑
               // List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prtdetailline where prtid=" + prtid1 + " and ppslid='" + ppslid1 + "'");
               //新逻辑
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prtdetailline where prtid=" + prtid1 + " and prtslid='" + prtslid + "'");

                if (CollectionUtils.isNotEmpty(bySql)) {
                    float receiveqty1 = 0;//入库数统计
                    float qualiquan1 = 0;
                    float sampquan1 = 0;
                    float returnqty1 = 0;//退货数统计
                    float arrquantity1 = 0;
                    for (int i = 0; i < bySql.size(); i++) {
                        Map<String, Object> map1 = bySql.get(i);
                        int pid = MapUtils.getIntValue(map1, "id");//采购接收明细行id
                        //获取检验结果，如果是退换货，需要汇总退换货数量
                        Float receiveqty = MapUtils.getFloat(map1, "receiveqty");//接收数量
                        Float qualiquan = MapUtils.getFloat(map1, "qualiquan");//合格数量
                        Float sampquan = MapUtils.getFloat(map1, "sampquan");//抽检数量
                        String insresults = MapUtils.getString(map1, "insresults");//检验结果
                        Float arrquantity = MapUtils.getFloat(map1, "arrquantity");//到货数量
                        Float orderqty = MapUtils.getFloat(map1, "orderqty");
                        if ("退货".equals(insresults)||"换货".equals(insresults)) {
                            //returnqty1 = returnqty1 + arrquantity;//检验结果不合格，统计退换数量
                            returnqty1 = returnqty1 + arrquantity;
                            handlerService.updateBySql("update gq_prtdetailline set returnqty="+arrquantity+" where id='"+pid+"'");
                        } else if ("合格".equals(insresults)) {
                            receiveqty1 = receiveqty1 + receiveqty;//检验结果合格，统计入库数量
                            qualiquan1 = qualiquan1 + qualiquan;//统计合格数量
                            handlerService.updateBySql("update gq_prtdetailline set returnqty="+0+" where id='"+pid+"'");
                        }
                        arrquantity1 = arrquantity1 + arrquantity;
                        sampquan1 = sampquan1 + sampquan;
                    }
                    //原逻辑
                    //handlerService.updateBySql("update gq_prtsummaryline set qualiquan =" + qualiquan1 + ",sampquan=" + sampquan1 + ",returnqty=" + returnqty1 + ",number=" + receiveqty1 + " where prtid='" + prtid1 + "' and ppslid='" + ppslid + "'");
                   //新逻辑
                    handlerService.updateBySql("update gq_prtsummaryline set qualiquan =" + qualiquan1 + ",sampquan=" + sampquan1 + ",returnqty=" + returnqty1 + ",number=" + receiveqty1 + " where prtid='" + prtid1 + "' and id='" + prtslid + "'");

                }
            }
        }
    }


    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        System.out.println("===> enter PurchaseReceiptHandler beforeExcuteFlow");
        System.out.println("===> app: " + app);
        System.out.println("===> id: " + id);
        System.out.println("===> flowNode: " + flowNode);
        System.out.println("===> op: " + op);
        if ("submit".equals(flowNode.getId())) {
            // 查询采购接收汇总行信息
            List<Map<String, Object>> prlList = handlerService.findBySql("select * from gq_prtsummaryline where prtid = " + id);
            if (CollectionUtils.isEmpty(prlList)) {
                return "请添加采购接收汇总行信息！";
            } else {
                // String instonum = MapUtils.getString(bySql.get(0),"instonum");
                List<Map<String, Object>> bySql3 = handlerService.findBySql("SELECT * from biz_attribute where object_id=(SELECT id from biz_object where name ='gq_prtdetailline') and required !=''");
                if (CollectionUtils.isNotEmpty(bySql3)){
                    for(int i=0;i<bySql3.size();i++){
                        Map<String, Object> map = bySql3.get(i);
                        String required = MapUtils.getString(map, "required");
                        if (required!=null||required!=""){
                            //log.info("required+++++++++++++++++++++++++++++++++++++" + required);
                            String columnname = MapUtils.getString(bySql3.get(i), "columnname");
                            // log.info("required+++++++++++++++++++++++++++++++++++++" + columnname);
                            List<Map<String, Object>> bySql4 = handlerService.findBySql("select acceptments,insresults from gq_prtdetailline where prtid='" +id+ "'");
                            if (CollectionUtils.isNotEmpty(bySql4)){
                                for (int z=0;z<bySql4.size();z++){
                                    Map<String, Object> map1 = bySql4.get(z);
                                    String acceptments = MapUtils.getString(map1, "acceptments");
                                    String insresults = MapUtils.getString(map1, "insresults");
                                    log.info("o+++++++++++++++++++++++++++++++++++++" + o);
                                    if (StringUtils.isEmpty(insresults)&&acceptments.contains("04")){
                                        log.info("required+++++++++++++++++++++++++++++++++++++" + insresults);
                                        i=z+1;
                                        return "该单据需生成验收单!";
                                    }else {
                                        log.info("required+++++++++++++++++++++++++++++++++++++" + insresults);
                                    }
                                }

                            }
                        }
                    }
                }

                for (int i=0;i<prlList.size();i++){
                    Map<String, Object> map = prlList.get(i);
                    String prtid = MapUtils.getString(map, "prtid");
                    String ppslid = MapUtils.getString(map, "ppslid");//原逻辑
                    String prtslid = MapUtils.getString(map, "id");//新逻辑
                    Float qualquantity = MapUtils.getFloat(map, "qualquantity");
                    List<Map<String, Object>> bySql = handlerService.findBySql("select arrquantity,warehousenum,binnum,insresults from gq_prtdetailline where prtid='" + prtid + "' and prtslid ='" + prtslid + "'");
                    if (CollectionUtils.isNotEmpty(bySql)){
                        float arrquantity0=0;
                        for (int j=0;j<bySql.size();j++){
                            Map<String, Object> map1 = bySql.get(j);
                            Float arrquantity = MapUtils.getFloat(map1, "arrquantity");
                            arrquantity0=arrquantity0+arrquantity;
                            String warehousenum = MapUtils.getString(map1, "warehousenum");
                            String binnum = MapUtils.getString(map1, "binnum");
                            String insresults = MapUtils.getString(map1, "insresults");
                            if(StringUtils.isEmpty(insresults)){
                                return "接收行检验结果不能为空！";
                            }
                            List<Map<String, Object>> bySql1 = handlerService.findBySql("select waremethod from gq_purchasereceipt where id='" + prtid + "'");
                            if (CollectionUtils.isNotEmpty(bySql1)){
                                Map<String, Object> map2 = bySql1.get(0);
                                String waremethod = MapUtils.getString(map2, "waremethod");
                                if (waremethod.equals("手工入库")){
                                    if (insresults.equals("合格")){
                                        log.info("+++++++++++++++++++");
                                        if (StringUtils.isEmpty(warehousenum)||StringUtils.isEmpty(binnum)){
                                            return "接收行库房库位信息不能为空！";
                                        }
                                    }

                                }
                            }
                        }
                        if (qualquantity.compareTo(arrquantity0)==0){

                         }else {
                            return ("采购接收行到货数量和不等于汇总行到货数量请查看！");
                    }
                    }
                }
                //验证明细行到货数量是否等于合格数量
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_prtdetailline where prtid='" + id + "'");
                if (CollectionUtils.isNotEmpty(bySql2)){
                    for (int i=0;i<bySql2.size();i++){
                        Map<String, Object> map = bySql2.get(i);
                        String insresults = MapUtils.getString(map, "insresults");
                        Float arrquantity = MapUtils.getFloat(map, "arrquantity");
                        Float qualiquan = MapUtils.getFloat(map, "qualiquan");
                        String itemnum = MapUtils.getString(map, "itemnum");
                        if (insresults.equals("合格")){
                            if (arrquantity.compareTo(qualiquan)!=0){

                                return "该单据"+itemnum+"物料到货数量与合格数量不符，请检查。";
                            }
                        }
                    }
                }
                /////////////////////////////////////
                //提交前，验证汇总行的数量是否等于，采购接收明细行、、、、
//                List<Map<String, Object>> nelList = handlerService.findBySql("select sum(receiveqty) as  receiveqtys from gq_prtdetailline where prtid = " + id+" and ppslid ="+prlList.get(0).get("ppslid"));
//                Object receiveqty = prlList.get(0).get("receiveqty");
//                Object receiveqtys = nelList.get(0).get("receiveqtys");
//                System.out.println("采购订单汇总行接收数================"+receiveqty);
//                System.out.println("采购订单明细汇总================"+receiveqtys);
//                if(!receiveqty.toString().equals(receiveqtys.toString())){
//                    return "采购接收行接收数量汇总和需要等于采购订单汇总行入库数";
//                }
//                List<Map<String, Object>> bySql = handlerService.findBySql("select qualquantity,qualiquan,receiveqty,sampquan from gq_prtsummaryline where prtid=" + id);
//                if (CollectionUtils.isNotEmpty(bySql)){
//                    for (int i=0;i<bySql.size();i++){
//                        Map<String, Object> map = bySql.get(i);
//                        Float qualquantity = MapUtils.getFloat(map, "qualquantity");//到货数量
//                        Float qualiquan = MapUtils.getFloat(map, "qualiquan");//合格数量
//                        Float receiveqty1 = MapUtils.getFloat(map, "receiveqty");//入库数量
//                        Float sampquan = MapUtils.getFloat(map, "sampquan");//抽检数量
//                        Float receivedqty = MapUtils.getFloat(map, "receivedqty");
//                        float qualiquan1=receivedqty+sampquan;
////                        if (abs(qualiquan-qualiquan1)<=1e-6){
////
////                        }else {
////                            return "采购汇总行合格数量需等于采购汇总行抽检数量加采购汇总行已接收数量之和";
////                        }
//                    }
//                }
            }
            //判断是否在验收，如果验收未通过审批，不允许提交流程申请
            List<Map<String, Object>> list1 = handlerService.findBySql("select receiptnum,type from gq_purchasereceipt where id=" + id + " and receiptnum in ( select receiptnum from gq_puraccept where status !='会签成功')");

            if (CollectionUtils.isNotEmpty(list1)) {
                return "该接收单对应验收单未审批完成！";
            }


//            String sql = "select receiptnum from gq_purchasereceipt where receiptnum in ( select receiptnum from gq_puraccept where status !='已批准')";
//            List<Map<String, Object>> list = handlerService.findBySql(sql);
//            boolean res= false;
//            if (CollectionUtils.isNotEmpty(list)) {
//                res = list.contains(list1.get(0).get("receiptnum"));
//            }
//            if(res){
//                return "采购接收单号添加到采购验收，验收未审批完，无法提交审批";
//            }
            //判断如果是审批入库，提交审批前，判断库房，货位是否填写
            List<Map<String, Object>> list2 = handlerService.findBySql("select waremethod from gq_purchasereceipt where id=" + id);

            if ("手动入库".equals(list2.get(0).get("waremethod"))) {
                List<Map<String, Object>> prList = handlerService.findBySql("select warehousenum,binnum,id,insresults from gq_prtdetailline where prtid = " + id);
                if (CollectionUtils.isNotEmpty(prList)) {
                    for (Map<String, Object> stringObjectMap : prList) {
                        String insresults = MapUtils.getString(stringObjectMap, "insresults");
                        if (insresults.equals("合格")) {
                            System.out.println("stringObjectMap.get(\"warehousenum\")====" + stringObjectMap.get("warehousenum"));
                            System.out.println("stringObjectMap.get(\"binnum\")====" + stringObjectMap.get("binnum"));
                            if ("".equals(stringObjectMap.get("warehousenum")) || "".equals(stringObjectMap.get("binnum")) || stringObjectMap.get("warehousenum") == null || stringObjectMap.get("binnum") == null) {
                                return "采购接收行请补全库房和货位信息在提交审批";
                            }
                        }

                    }
                }

            }
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prtdetailline where prtid='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                for (int i=0;i<bySql.size();i++){
                    Map<String, Object> map = bySql.get(i);
                    String whepasaccep = MapUtils.getString(map, "whepasaccep");
                    String insresults = MapUtils.getString(map, "insresults");//检验结果
                    String itemnum = MapUtils.getString(map, "itemnum");
                    if (insresults.equals("合格")){
                        if (whepasaccep.equals("否")){
                            return "物料"+itemnum+"未完成点验，请检查！";
                        }
                    }

                }
            }
            //流程提交前判定占用采购接收数量
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_prtdetailline where prtid='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql1)){
                for (int i=0;i<bySql1.size();i++){
                    Map<String, Object> map = bySql1.get(i);
                    String polid = MapUtils.getString(map, "polid");//采购订单明细行id
                    Float arrquantity = MapUtils.getFloat(map, "arrquantity");//到货数量
                    float quantity = 0;
                    List<Map<String, Object>> bySql4 = handlerService.findBySql("select t.* from gq_prtdetailline t left join gq_purchasereceipt a on t.prtid=a.id where t.polid='" + polid + "' and a.status!='新建' and a.status!='已作废' and a.status!='已批准' and a.status!='已验收' and a.status!='验收中'");
                    if (CollectionUtils.isNotEmpty(bySql4)){
                        for (int j=0;j<bySql4.size();j++){
                            Map<String, Object> map2 = bySql4.get(j);
                            Float arrquantity1 = MapUtils.getFloat(map2, "arrquantity");
                            quantity=quantity+arrquantity1;//统计审批中到货数量
                        }
                        arrquantity=arrquantity+quantity;
                    }
                        List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_poline where id='" + polid + "'");
                        Float grantqty = (float) 0;
                        if (CollectionUtils.isNotEmpty(bySql2)){
                            Map<String, Object> map1 = bySql2.get(0);
                            grantqty = MapUtils.getFloat(map1, "unreceivedqty");//采购订单数量
                        }
                        if (grantqty.compareTo(arrquantity)<0){
                            int y = i + 1;
                            float grantqty1 = grantqty - quantity;
                            if (grantqty1<=0){
                                return "采购接收物料第" + y + "条数据中部分物料被人占用，当前采购订单剩余0，请重新选择物料！";
                            }else {
                                return "采购接收物料第" + y + "条数据中部分物料被人占用，当前采购订单剩余"+grantqty1+"，请重新选择物料！";
                            }
                        }

                }
            }
        }


//        List<Map<String, Object>> bySql = handlerService.findBySql("select acceptments from gq_purchasereceipt where id=" + id);
//        String acceptments = org.apache.commons.collections4.MapUtils.getString(bySql.get(0), "acceptments");
//        if (acceptments.equals("04")) {
//            List<Map<String, Object>> bySql1 = handlerService.findBySql("select insresults from gq_prtsummaryline where prtid='" + id + "'");
//            if (bySql1 != null && bySql1.size() != 0) {
//                for (int i = 0; i < bySql1.size(); i++) {
//                    Map<String, Object> map = bySql1.get(i);
//                    String insresults = MapUtils.getString(map, "insresults");
//                    if (insresults == null || insresults == "") {
//                        return "采购接收行数据未验收";
//                    }
//                }
//
////                if (list!=null||list.size()!=0){
////
////                    for (int j=0;j<list.size();j++){
////                        log.info("jjjjj+++++++++++++++++++++++++++++++++++++++++++++++++++++++"+list.get(j));
////                        string=string+list.get(j);
////                        log.info("sssss+++++++++++++++++++++++++++++++++++++++++++++++++++++++"+string);
////                    }
////
////                }
//
//            }
//        }

        return super.beforeExcuteFlow(app, id, flowNode, op);
    }

    @Override
    public void afterMoveNode(String app, Long id) throws Exception {
        System.out.println("===> enter PurchaseReceiptHandler afterMoveNode");
        System.out.println("===> app: " + app);
        System.out.println("===> id: " + id);
        if (app.equals("purchasereceiptApp")){
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_purchasereceipt where id='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                String the="否";
                handlerService.updateBySql("update gq_purchasereceipt set whether='"+the+"' where id='"+id+"'");
            }
        }
        super.afterMoveNode(app, id);
    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        System.out.println("===> enter PurchaseReceiptHandler afterExcuteFlow");
        System.out.println("===> app: " + app);
        System.out.println("===> id: " + id);
        System.out.println("===> flowNode: " + flowNode);
        System.out.println("===> op: " + op);
        System.out.println("===> event: " + event);
        if (flowNode.getId().equals("complete") && op.isFlag()) {
            //新增流程结束后将价格录入到物料主数据
            List<Map<String, Object>> bySql = handlerService.findBySql("select itemnum,unitcost from gq_prtsummaryline where prtid =" + id);
            for (Map<String, Object> map : bySql) {
                String itemnum = MapUtils.getString(map, "itemnum");
                Float unitcost = MapUtils.getFloat(map, "unitcost");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String createtime = sdf.format(new Date());
                handlerService.updateBySql("insert into gq_hispricemater (itemnum,unitcost,createtime) values ('" + itemnum + "'," + unitcost + ",'" + createtime + "')");
            }
            //
            List<Map<String, Object>> pcList = handlerService.findBySql("select receiptnum, type,waremethod from gq_purchasereceipt where id = " + id);
            Map<String, Object> pcMap = pcList.get(0);
            String type = MapUtils.getString(pcMap, "type");
            String waremethod = MapUtils.getString(pcMap, "waremethod");//入库方式

            //审批入库完，接收，退/换，给采购申请人发送消息
            List<Map<String, Object>> prtList = handlerService.findBySql("select * from gq_prtdetailline where prtid = " + id);
            //先不执行发消息逻辑
            sendMessage(prtList);
            HashSet<Long> strings = new HashSet<>();

            if ("接收".equals(type)) {
                if("手工入库".equals(waremethod)){
                    BigDecimal bigDecimal3 = new BigDecimal("0");//未接收金额和
                    for (int j=0;j<prtList.size();j++){
                        Map<String, Object> map = prtList.get(j);
                        String insresults = MapUtils.getString(map, "insresults");
                        Long prtid = MapUtils.getLong(map, "prtid");//采购接收id
                        Long prtslid1 = MapUtils.getLong(map, "prtslid");//采购接收汇总id
                        if (insresults.equals("合格")){
                            try {
                                strings.add(prtslid1);
                                // 处理采购接收申请接收逻辑
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }else if(insresults.equals("退货")){
                            String polid = MapUtils.getString(map, "polid");//采购订单行id
                            String unreceivedqty = MapUtils.getString(map, "unreceivedqty");//未接收数量
                            String unitcost = MapUtils.getString(map, "unitcost");//单价
                            BigDecimal bigDecimal = new BigDecimal(unreceivedqty);
                            BigDecimal bigDecimal1 = new BigDecimal(unitcost);
                            BigDecimal bigDecimal2 = new BigDecimal("0");
                            bigDecimal2=bigDecimal.multiply(bigDecimal1);//未接收金额
                            bigDecimal3=bigDecimal3.add(bigDecimal2);
                        }
                    }
                    //退货时更改采购订单总金额
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select ponum from gq_purchasereceipt where id='" + id + "'");
                    if(CollectionUtils.isNotEmpty(bySql1)){
                        String ponum = MapUtils.getString(bySql1.get(0), "ponum");//采购订单编号
                        List<Map<String, Object>> bySql2 = handlerService.findBySql("select toderount from gq_po where ponum='" + ponum + "'");
                        if (CollectionUtils.isNotEmpty(bySql2)){
                            String toderount = MapUtils.getString(bySql2.get(0), "toderount");//采购订单总金额
                            BigDecimal bigDecimal = new BigDecimal(0);
                            if(ToolUtil.isNotEmpty(toderount)){
                                bigDecimal = new BigDecimal(toderount);
                            }
                            bigDecimal=bigDecimal.subtract(bigDecimal3);
                            handlerService.updateBySql("update gq_po set toderount="+bigDecimal+" where ponum='"+ponum+"'");
                        }
                    }
                    if (CollectionUtils.isNotEmpty(strings)){
                        List<Long> strings1 = new ArrayList<>(strings);
                        for (int i=0;i<strings1.size();i++){
                            Long prtslid1 = strings1.get(i);
                            dealReceiptPO(prtslid1);
                        }
                    }


                    // 更新供应商的到货率和合格率
                    calculationPrPa(id);
                    //处理供应商台账返回数据问题
                    dealReceiptPO11(id);
                }
                //审批入库
                try {
                    appwarehousing(id);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //返回采购申请入库数量
                try{
                    repurchquest(id);
                } catch (Exception e){
                    e.printStackTrace();
                }
                for (int j=0;j<prtList.size();j++){
                    Map<String, Object> map = prtList.get(j);
                    String insresults = MapUtils.getString(map, "insresults");
                    Long prtid = MapUtils.getLong(map, "prtslid");
                    if (insresults.equals("退货")){
                        //退换货
                        try {
                            dealReturnExgPO(prtid);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            } else if ("退/换".equals(type)) {
                // 处理采购接收申请退换逻辑
                dealReturnExgPO(id);
            }
        }
    }

    /**
     * 采购接收审批入库，给对应采购申请人发消息
     *
     * @param prtList
     */
    private void sendMessage(List<Map<String, Object>> prtList) {
        if (CollectionUtils.isNotEmpty(prtList)) {
//            List<Map<String, Object>> bySql = handlerService.findBySql("select messagenum from gq_message order by messagenum desc limit 1");
//            String messagenum = "1001";
//            if (CollectionUtils.isNotEmpty(bySql)) {
//                Map<String, Object> map = bySql.get(0);
//                messagenum = MapUtils.getString(map, "messagenum");
//                Integer integer = Integer.valueOf(messagenum);
//                int i = integer + 1;
//                messagenum = String.valueOf(i);
//            }
            for (Map<String, Object> map : prtList) {
                String applyby = MapUtils.getString(map, "applyby");
                String itemnum = MapUtils.getString(map, "itemnum");
                String itemdesc = MapUtils.getString(map, "itemdesc");
                Date createtime = MapUtil.getDate(map, "createtime");
                String createuser = MapUtil.getStr(map, "createuser");
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select nickname from sys_user where id = '" + createuser + "'");
                String createuserdesc = MapUtil.getStr(map, "createuserdesc");
                if(CollectionUtils.isNotEmpty(bySql2)){
                    createuserdesc = MapUtils.getString(bySql2.get(0),"nickname");
                }

                String insresults = MapUtil.getStr(map, "insresults");//验收结果
                BlMessage message = new BlMessage();
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select id,nickname from sys_user where field10 = " + applyby + " limit 1");
                if (CollectionUtils.isNotEmpty(bySql1)) {
                    Map<String, Object> map1 = bySql1.get(0);
                    String id = MapUtils.getString(map1, "id");
                    String nickname = MapUtils.getString(map1, "nickname");
                    message.setRecipient(id);
                    message.setRecipientname(nickname);
                    message.setCreatetime(createtime);
                    message.setIsshow("未读");
                    StringBuilder str = new StringBuilder();
                    if ("合格".equals(insresults)) {
                        str.append(nickname).append(",您申请采购物料编码为" + itemnum + "物料名称为" + itemdesc + "已入库");
                    } else if ("退货".equals(insresults)) {
                        str.append(nickname).append(",您申请采购物料编码为" + itemnum + "物料名称为" + itemdesc + "经检验，需退货处理");
                    } else if ("换货".equals(insresults)) {
                        str.append(nickname).append(",您申请采购物料编码为" + itemnum + "物料名称为" + itemdesc + "经检验，需换货处理");
                    }
                    message.setContent(str.toString());
                    message.setTitle("采购接收审批");
//                    message.setMessagenum(messagenum);
                    message.setCreateuser(createuser);
                    message.setCreateuserdesc(createuserdesc);
                    message.setStatus("未读");
                    message.setVersion("1");
                    Map<String, Object> map2 = new HashMap<>();
                    handlerService.addBizNum("messageApp","gq_message",map2);
                    String messagenum = MapUtils.getString(map2, "messagenum");
                    message.setMessagenum(messagenum);
                    int res = messageService.addMessage(message);
                    System.out.println("添加状态:" + res);
                }

            }
        }
    }

    /**
     * 组织插入采购接收退换明细行信息
     *
     * @param data
     */
    private void combinePrtReturnDetail(Map<String, Object> data) throws Exception {
        Integer prtslid = MapUtils.getInteger(data, "prtslid");
        Integer prtid = MapUtils.getInteger(data, "prtid");
        Integer poid = MapUtils.getInteger(data, "poid");
        Integer ppslid = MapUtils.getInteger(data, "ppslid");
        String createuser = MapUtils.getString(data, "createuser");
        String deptcode = MapUtils.getString(data, "deptcode");
        /*
         * 复制采购订单明细行
         */
        // 查询采购订单明细行
        List<Map<String, Object>> prtdlList = handlerService.findBySql("select * from gq_prtdetailline t where not exists (select 1 from gq_prtdetailline a where a.prtdlid = t.prtdlid and prtslid = " + prtslid + ") and prtslid = " + prtslid);

        if (CollectionUtils.isNotEmpty(prtdlList)) {
            List<Map<String, Object>> prtdlDatas = new ArrayList<>();
            for (Map<String, Object> tmepMap : prtdlList) {
                float orderqty = (float) tmepMap.get("orderqty");

                // 组织采购订单明细数据
                Map<String, Object> prtdlMap = new HashMap<>();
                prtdlMap.put("prtslid", prtslid);
                prtdlMap.put("prtid", prtid);
                prtdlMap.put("ppslid", ppslid);
                prtdlMap.put("poid", poid);
                prtdlMap.put("ponum", tmepMap.get("ponum"));
                prtdlMap.put("ppid", tmepMap.get("ppid"));
                prtdlMap.put("pplid", tmepMap.get("id"));
                prtdlMap.put("proid", tmepMap.get("proid"));
                prtdlMap.put("taskid", tmepMap.get("taskid"));
                prtdlMap.put("prid", tmepMap.get("prid"));
                prtdlMap.put("prlid", tmepMap.get("prlid"));
                prtdlMap.put("pplinenum", tmepMap.get("pplinenum"));
                prtdlMap.put("ppnum", tmepMap.get("ppnum"));
                prtdlMap.put("prnum", tmepMap.get("prnum"));

                prtdlMap.put("requestedby", createuser);
                prtdlMap.put("reqdeptcode", deptcode);

                prtdlMap.put("itemtype", tmepMap.get("itemtype"));
                prtdlMap.put("itemnum", tmepMap.get("itemnum"));
                prtdlMap.put("itemdesc", tmepMap.get("itemdesc"));
                prtdlMap.put("spemodel", tmepMap.get("spemodel"));
                prtdlMap.put("qualitygrade", tmepMap.get("qualitygrade"));
                prtdlMap.put("manufacturer", tmepMap.get("manufacturer"));
                prtdlMap.put("packform", tmepMap.get("packform"));
                prtdlMap.put("maintechtors", tmepMap.get("maintechtors"));
                prtdlMap.put("model", tmepMap.get("model"));

                prtdlMap.put("orderqty", orderqty);
                prtdlMap.put("returnqty", tmepMap.get("receiveqty"));
                prtdlMap.put("returnedqty", tmepMap.get("returnedqty"));
                prtdlMap.put("returnableqty", tmepMap.get("returnableqty"));

                prtdlMap.put("warehousenum", tmepMap.get("warehousenum"));
                prtdlMap.put("binnum", tmepMap.get("binnum"));
                prtdlMap.put("batchnum", tmepMap.get("batchnum"));
                prtdlMap.put("unit", tmepMap.get("unit"));
                prtdlMap.put("whepasaccep", "否");
                prtdlMap.put("expirydate", tmepMap.get("expirydate"));
                prtdlMap.put("productiondate", tmepMap.get("productiondate"));
                prtdlMap.put("receivetolerance", tmepMap.get("receivetolerance"));
                prtdlMap.put("returnreason", tmepMap.get("returnreason"));
                prtdlMap.put("convertfactor", tmepMap.get("convertfactor"));

                prtdlMap.put("orderunit", tmepMap.get("orderunit"));

                prtdlMap.put("unitcost", tmepMap.get("unitcost"));
                prtdlMap.put("taxcode", tmepMap.get("taxcode"));
                prtdlMap.put("taxrate", tmepMap.get("taxrate"));
                prtdlMap.put("linecost", tmepMap.get("linecost"));

                prtdlMap.put("isinspection", tmepMap.get("isinspection"));
                prtdlMap.put("inspectionreq", tmepMap.get("inspectionreq"));
                prtdlMap.put("whfournew", tmepMap.get("whfournew"));
                prtdlMap.put("whethdangerous", tmepMap.get("whethdangerous"));
                prtdlMap.put("advisupplier", tmepMap.get("advisupplier"));
                prtdlMap.put("contacts", tmepMap.get("contacts"));
                prtdlMap.put("phone", tmepMap.get("phone"));
                prtdlMap.put("rearecommendation", tmepMap.get("rearecommendation"));
                prtdlMap.put("reqdeliverydate", tmepMap.get("reqdeliverydate"));
                prtdlMap.put("acceptments", tmepMap.get("acceptments"));
                String acceptmentsnew =StringUtil.setString(MapUtils.getString(tmepMap,"acceptments")) ;//检验要求中文显示
                prtdlMap.put("acceptmentsnew", tmepMap.get("acceptmentsnew"));
                prtdlMap.put("wheprocuremen", tmepMap.get("wheprocuremen"));
                prtdlMap.put("commerceorder", tmepMap.get("commerceorder"));
                prtdlMap.put("reasonpur", tmepMap.get("reasonpur"));

                prtdlMap.put("production", tmepMap.get("production"));
                prtdlMap.put("requiredtime", tmepMap.get("requiredtime"));
                prtdlMap.put("unifiedno", tmepMap.get("unifiedno"));
                prtdlMap.put("researchmode", tmepMap.get("researchmode"));
                prtdlMap.put("productmode", tmepMap.get("productmode"));
                prtdlMap.put("purchasemethod", tmepMap.get("purchasemethod"));
                prtdlMap.put("invitationmethod", tmepMap.get("invitationmethod"));
                prtdlMap.put("purchasenote", tmepMap.get("purchasenote"));
                prtdlMap.put("occupnot", tmepMap.get("occupnot"));
                prtdlMap.put("applyby", tmepMap.get("applyby"));

                prtdlDatas.add(prtdlMap);
            }

            // 批量插入采购接收明细行信息
            handlerService.batchInsert("purchasereceiptApp", "gq_prtdetailline", prtdlDatas);
        }
    }

    /**
     * 组织插入采购接收明细行信息
     *
     * @param data
     */
    private void combinePrtDetail(Map<String, Object> data) throws Exception {
        Integer prtslid = MapUtils.getInteger(data, "id");
        Integer prtid = MapUtils.getInteger(data, "prtid");
        Integer poid = MapUtils.getInteger(data, "poid");
        String ponum = MapUtils.getString(data, "ponum");
        Integer ppid = MapUtils.getInteger(data, "ppid");
        Integer ppslid = MapUtils.getInteger(data, "ppslid");
        String createuser = MapUtils.getString(data, "createuser");
        String deptcode = MapUtils.getString(data, "deptcode");
        String poslid = MapUtils.getString(data, "poslid");
        /*
         * 复制采购订单明细行
         */
        // 查询采购订单明细行
        //List<Map<String, Object>> polList = handlerService.findBySql("select * from gq_poline t where not exists (select 1 from gq_prtdetailline a where a.ppslid = t.ppslid and ppid = " + ppid + " and ppslid = " + ppslid + ") and ppid = " + ppid + " and ppslid = " + ppslid);
        List<Map<String, Object>> polList = handlerService.findBySql("select * from gq_poline t where poslid='"+poslid+"'  and unreceivedqty>0 and arrquantity>0 and ponum='" + ponum + "'");

        if (CollectionUtils.isNotEmpty(polList)) {
            List<Map<String, Object>> prtdlDatas = new ArrayList<>();
            for (Map<String, Object> polMap : polList) {
                float orderqty = (float) polMap.get("orderqty");

                // 组织采购订单明细数据
                Map<String, Object> prtdlMap = new HashMap<>();
                //创建uuid
                String uid = IdUtil.simpleUUID();
                prtdlMap.put("uuidprice",uid);
                prtdlMap.put("prtslid", prtslid);
                prtdlMap.put("prtid", prtid);
                prtdlMap.put("ppslid", ppslid);
                prtdlMap.put("pplid",polMap.get("pplid"));//采购计划明细行id
                prtdlMap.put("poid", poid);
                prtdlMap.put("ponum", ponum);
                prtdlMap.put("ppid", polMap.get("ppid"));
                prtdlMap.put("polid", polMap.get("id"));//采购订单明细行id 赋值给采购接收行的polid
                prtdlMap.put("proid", polMap.get("proid"));
                prtdlMap.put("taskid", polMap.get("taskid"));
                prtdlMap.put("prid", polMap.get("prid"));
                prtdlMap.put("prlid", polMap.get("prlid"));
                String prlid = MapUtils.getString(polMap, "prlid");
                //外协订单，给会签人赋值
                try {
                    String applicationnum =  (String)polMap.get("applicationnum");
                    if(ToolUtil.isNotEmpty(applicationnum)){
                        List<Map<String, Object>> bySql = handlerService.findBySql("select createuser from gq_conapplication where applicationnum ='" + applicationnum + "'");
                        if(CollectionUtils.isNotEmpty(bySql)){
                            Map<String, Object> map = bySql.get(0);
                            String createuser1 = MapUtils.getString(map, "createuser");
                            List<Map<String, Object>> bySql1 = handlerService.findBySql("select field10,username,nickname from sys_user where id ='" + createuser1 + "'");
                            prtdlMap.put("usernameid",createuser1);
                            prtdlMap.put("username",bySql1.get(0).get("username"));
                            prtdlMap.put("nickname",bySql1.get(0).get("nickname"));
                            prtdlMap.put("applicant",bySql1.get(0).get("field10"));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prline where id ='" + prlid + "'");
                if(CollectionUtils.isNotEmpty(bySql)){
                    Map<String, Object> map = bySql.get(0);
                    String isdpaanalysis = MapUtils.getString(map, "isdpaanalysis");
                    String specialrequirements = MapUtils.getString(map, "specialrequirements");
                    String isfactoryacceptance = MapUtils.getString(map, "isfactoryacceptance");
                    String componentsparts = MapUtils.getString(map, "componentsparts");
                    String isspeciallymade = MapUtils.getString(map, "isspeciallymade");
                    String createuser1 = MapUtils.getString(map, "createuser");
                    prtdlMap.put("isdpaanalysis", isdpaanalysis);
                    prtdlMap.put("specialrequirements",specialrequirements);
                    prtdlMap.put("isfactoryacceptance",isfactoryacceptance);
                    prtdlMap.put("componentsparts",componentsparts);
                    prtdlMap.put("isspeciallymade",isspeciallymade);
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select field10,username,nickname from sys_user where id ='" + createuser1 + "'");
                    prtdlMap.put("usernameid",createuser1);
                    prtdlMap.put("username",bySql1.get(0).get("username"));
                    prtdlMap.put("nickname",bySql1.get(0).get("nickname"));
                    prtdlMap.put("applicant",bySql1.get(0).get("field10"));
                }



                prtdlMap.put("pplinenum", polMap.get("pplinenum"));
                prtdlMap.put("ppnum", polMap.get("ppnum"));
                prtdlMap.put("prnum", polMap.get("prnum"));

                prtdlMap.put("requestedby", createuser);
                prtdlMap.put("reqdeptcode", deptcode);

                prtdlMap.put("itemtype", polMap.get("itemtype"));
                prtdlMap.put("itemnum", polMap.get("itemnum"));
                prtdlMap.put("itemdesc", polMap.get("itemdesc"));

                prtdlMap.put("qualitygrade", polMap.get("qualitygrade"));
                prtdlMap.put("manufacturer", polMap.get("manufacturer"));
                prtdlMap.put("packform", polMap.get("packform"));
                prtdlMap.put("maintechtors", polMap.get("maintechtors"));
                prtdlMap.put("model", polMap.get("model"));//型号
                prtdlMap.put("spemodel", polMap.get("spemodel"));//品牌
                prtdlMap.put("specifications", polMap.get("specifications"));//规格
                prtdlMap.put("orderqty", orderqty);
                prtdlMap.put("arrquantity",orderqty);
                //prtdlMap.put("receiveqty", polMap.get("unreceivedqty"));
                prtdlMap.put("receivedqty", polMap.get("receivedqty"));
                prtdlMap.put("unreceivedqty", polMap.get("unreceivedqty"));
                prtdlMap.put("returnedqty", 0);
                prtdlMap.put("returnableqty", polMap.get("unreceivedqty"));
                prtdlMap.put("returnqty", 0);

                prtdlMap.put("orderunit", polMap.get("orderunit"));
                prtdlMap.put("unitcost", polMap.get("unitcost"));
                prtdlMap.put("taxcode", polMap.get("taxcode"));
                prtdlMap.put("taxrate", polMap.get("taxrate"));

                String linecost = MapUtils.getString(polMap, "linecost");
                BigDecimal bigDecimal1 = new BigDecimal(linecost);
                prtdlMap.put("linecost", bigDecimal1);
                //prtdlMap.put("reamount", bigDecimal1);//入库金额

                prtdlMap.put("occupnot", polMap.get("occupnot"));
                prtdlMap.put("applyby", polMap.get("applyby"));

                prtdlMap.put("warehousenum", polMap.get("warehousenum"));
                //prtdlMap.put("binnum", polMap.get("binnum"));
                //prtdlMap.put("batchnum", polMap.get("batchnum"));

                String ymd = DateUtiles.getYmdNew(new Date());
                String sql = "select max(batchnum)+1 as batchnum from gq_prtdetailline where batchnum like '%" + ymd + "%'";
                System.out.println("sql获取批次号===========" + sql);
                List<Map<String, Object>> list = handlerService.findBySql(sql);

                System.out.println("list.get(0)====================" + list.get(0) + "============");
                if (list.get(0) != null) {
                    prtdlMap.put("batchnum", list.get(0).get("batchnum"));
                } else {
                    prtdlMap.put("batchnum", ymd + "000000");
                }
                System.out.println("获取批次号===========" + prtdlMap.get("batchnum"));
                prtdlMap.put("unit", polMap.get("unit"));
                prtdlMap.put("whepasaccep", "否");
                prtdlMap.put("expirydate", polMap.get("expirydate"));
                prtdlMap.put("productiondate", polMap.get("productiondate"));
                prtdlMap.put("receivetolerance", polMap.get("receivetolerance"));
                prtdlMap.put("returnreason", polMap.get("returnreason"));
                prtdlMap.put("convertfactor", polMap.get("convertfactor"));

                prtdlMap.put("isinspection", polMap.get("isinspection"));
                prtdlMap.put("inspectionreq", polMap.get("inspectionreq"));
                prtdlMap.put("whfournew", polMap.get("whfournew"));
                prtdlMap.put("whethdangerous", polMap.get("whethdangerous"));
                prtdlMap.put("advisupplier", polMap.get("advisupplier"));
                prtdlMap.put("contacts", polMap.get("contacts"));
                prtdlMap.put("phone", polMap.get("phone"));
                prtdlMap.put("rearecommendation", polMap.get("rearecommendation"));
                prtdlMap.put("reqdeliverydate", polMap.get("reqdeliverydate"));
                prtdlMap.put("acceptments", polMap.get("acceptments"));
                //String acceptmentsnew =StringUtil.setString(MapUtils.getString(polMap,"acceptments")) ;//检验要求
                prtdlMap.put("acceptmentsnew", polMap.get("acceptmentsnew"));
                prtdlMap.put("wheprocuremen", polMap.get("wheprocuremen"));
                prtdlMap.put("commerceorder", polMap.get("commerceorder"));
                prtdlMap.put("reasonpur", polMap.get("reasonpur"));

                prtdlMap.put("production", polMap.get("production"));
                prtdlMap.put("requiredtime", polMap.get("requiredtime"));
                prtdlMap.put("unifiedno", polMap.get("unifiedno"));
                prtdlMap.put("researchmode", polMap.get("researchmode"));
                prtdlMap.put("productmode", polMap.get("productmode"));
                prtdlMap.put("purchasemethod", polMap.get("purchasemethod"));
                prtdlMap.put("invitationmethod", polMap.get("invitationmethod"));
                prtdlMap.put("purchasenote", polMap.get("purchasenote"));
               // prtdlMap.put("componentsparts", polMap.get("componentsparts"));
               // prtdlMap.put("isdpaanalysis", polMap.get("isdpaanalysis"));
               // prtdlMap.put("specialrequirements", polMap.get("specialrequirements"));
              //  prtdlMap.put("isspeciallymade", polMap.get("isspeciallymade"));
               // prtdlMap.put("isfactoryacceptance", polMap.get("isfactoryacceptance"));
                prtdlMap.put("subjectno", polMap.get("subjectno"));
                prtdlMap.put("orderunit", polMap.get("orderunit"));
                prtdlMap.put("qualitygrade", polMap.get("qualitygrade"));
                prtdlMap.put("packform", polMap.get("packform"));
                prtdlMap.put("purchasemethod", polMap.get("purchasemethod"));
                prtdlMap.put("type",polMap.get("type"));
                prtdlMap.put("accertificate","0");

                //prtdlDatas.add(prtdlMap);
                handlerService.insert("gq_prtdetailline", prtdlMap);
            }

            // 批量插入采购接收明细行信息
            // handlerService.batchInsert("purchasereceiptApp", "gq_prtdetailline", prtdlDatas);
            List<Map<String, Object>> bySql = handlerService.findBySql("select qualiquan,receiveqty,id from gq_prtdetailline where acceptments not like '%04%' and prtid='" + prtid + "' and ppslid='" + ppslid + "'");
            if (CollectionUtils.isNotEmpty(bySql)) {
                for (int i = 0; i < bySql.size(); i++) {
                    Map<String, Object> map = bySql.get(i);
                    Float qualiquan = MapUtils.getFloat(map, "qualiquan");//合格数量
                    Float receiveqty = MapUtils.getFloat(map, "receiveqty");//入库数量
                    Integer id = MapUtils.getInteger(map, "id");
                    handlerService.updateBySql("update gq_prtdetailline set qualiquan=receiveqty where id= " + id);
                }
            }

        }
    }

    /**
     * 根据采购接收处理采购订单信息
     *
     * @param prtid
     */
    public void dealReceiptPO(Long prtslid1) {
        //修改入库数量，已接受数量和未接收数量
        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prtsummaryline where id=" + prtslid1);
        if (CollectionUtils.isNotEmpty(bySql)) {
            for (int z = 0; z < bySql.size(); z++) {
                Map<String, Object> map = bySql.get(z);
                Float number = MapUtils.getFloat(map, "number");//接受行入库数量
                Integer id = MapUtils.getInteger(map, "id");//订单汇总行id
                Float receivedqty = MapUtils.getFloat(map, "receivedqty");//已接受数量
                Float unreceivedqty = MapUtils.getFloat(map, "unreceivedqty");//未接收数量
                Float qualiquan = MapUtils.getFloat(map, "qualiquan");//合格数量
                //之前逻辑
//                float receivedqty1 = receivedqty + number;
//                float unreceivedqty1 = unreceivedqty - receivedqty;
//                if(unreceivedqty1<0.0f){
//                    unreceivedqty1 = 0f;
//                }
                //未接受数量=未接受数量-入库数量
                float receivedqty1 = receivedqty + qualiquan;
                float unreceivedqty1 = unreceivedqty - qualiquan;
                if(unreceivedqty1<0.0f){
                    unreceivedqty1 = 0f;
                }

                handlerService.updateBySql("update gq_prtsummaryline set receiveqty =" + number + ",receivedqty=" + receivedqty1 + ",unreceivedqty=" + unreceivedqty1 + " where id=" + id);
            }
        }
        // 查询采购接收汇总行信息
        //List<Map<String, Object>> prtslList = handlerService.findBySql("SELECT receiveqty, poslid, id from gq_prtsummaryline where prtid = " + prtid);
        //查询入库数量大于0的汇总行数据
        List<Map<String, Object>> prtslList = handlerService.findBySql("SELECT ponum,unitcost,prtid,receiveqty, poslid, ppslid,id,receivedqty,unreceivedqty,totalcost,qualquantity,qualiquan from gq_prtsummaryline where id = " + prtslid1 + " and receiveqty >0");
        BigDecimal decimal = new BigDecimal("0");
        String ponum="";
        if (CollectionUtils.isNotEmpty(prtslList)) {
            for (Map<String, Object> prtslMap : prtslList) {
                Integer prtslid = MapUtils.getInteger(prtslMap, "id");
                Integer poslid = MapUtils.getInteger(prtslMap, "poslid");
                Integer ppslid = MapUtils.getInteger(prtslMap, "ppslid");
                Long prtid = MapUtils.getLong(prtslMap, "prtid");//主表id
                Float receiveqty = MapUtils.getFloat(prtslMap, "qualiquan");//之前是按照入库数，现在改成按照合格数
                Float receivedqty = MapUtils.getFloat(prtslMap, "receivedqty");
                Float unreceivedqty = MapUtils.getFloat(prtslMap, "unreceivedqty");
                Float qualquantity = MapUtils.getFloat(prtslMap, "qualquantity");//到货数量
                Float totalcost = MapUtils.getFloat(prtslMap, "totalcost");//订单汇总行接收总额

                Float unitcost = MapUtils.getFloat(prtslMap, "unitcost");//单价
                ponum = MapUtils.getString(prtslMap, "ponum");
//                //修改未接收数量和接收数量
//                receivedqty=receivedqty+receiveqty;
//                unreceivedqty=unreceivedqty-receiveqty;
//                handlerService.updateBySql("update gq_prtsummaryline set receivedqty="+receivedqty+",unreceivedqty="+unreceivedqty+" where id="+prtslid);
                // 查询采购订单行信息
                List<Map<String, Object>> polList = handlerService.findBySql("select receivedqty, orderqty, inspectqty,receivedtotalcost,qualquantity from gq_posline where id = " + poslid);
                Map<String, Object> polMap = polList.get(0);
                Float poslorderqty = MapUtils.getFloat(polMap, "orderqty");// 采购数量
                Float poslreceivedqty = MapUtils.getFloat(polMap, "receivedqty");// 接收数量
                Float poslinspectqty = MapUtils.getFloat(polMap, "inspectqty");// 验收数量
                Float receivedtotalcost = MapUtils.getFloat(polMap, "receivedtotalcost");// 接收总额
                Float qualquantity1 = MapUtils.getFloat(polMap, "qualquantity");//到货数量
// 计算数量
                qualquantity1=qualquantity1-qualquantity;//到货数量
                poslreceivedqty = poslreceivedqty + receiveqty;
                Float poslunreceivedqty = poslorderqty - poslreceivedqty;
                poslinspectqty = poslinspectqty + receiveqty;
                Float posluninspectqty = poslorderqty - poslinspectqty;

                receivedtotalcost = receivedtotalcost + totalcost;
                String receiptscomplete = "已接收完成";
                if (!poslorderqty.equals(poslreceivedqty)) {
                    receiptscomplete = "已完成部分接收";
                }

                // 更新采购订单行数据
                /*receiptscomplete:接收完成或者部分接收
                  inspectqty：已验收数量
                  receivedqty：已接收数量
                  uninspectqty：未验收数量
                  unreceivedqty：未接收数量
                * */


                handlerService.updateBySql("UPDATE gq_posline set receiptscomplete='" + receiptscomplete
                        + "', inspectqty = " + poslinspectqty + ", receivedqty =" + poslreceivedqty
                        + ", uninspectqty =" + posluninspectqty + ", unreceivedqty =" + poslunreceivedqty + ",receivedtotalcost = " + receivedtotalcost + ",qualquantity="+qualquantity1+"  where id = " + poslid);
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select receivedqty,unitcost from gq_posline where id = " + poslid);
                if (CollectionUtils.isNotEmpty(bySql1)){
                    Map<String, Object> map = bySql1.get(0);
                    String receivedqty1 = MapUtils.getString(map, "receivedqty");
                    String unitcost1 = MapUtils.getString(map, "unitcost");
                    BigDecimal receivedqty2 = new BigDecimal(receivedqty1);
                    BigDecimal unitcost2 = new BigDecimal(unitcost1);
                    BigDecimal unpaidamts = new BigDecimal("0");
                    unpaidamts=receivedqty2.multiply(unitcost2);
                    handlerService.updateBySql("UPDATE gq_posline set unpaidamts='"+unpaidamts+"' where id = " + poslid);
                }
                //获取最新已接收数，更新采购订单主表可开发票金额,待开发票金额

                // 更新采收接收行可退换数量
                handlerService.updateBySql("UPDATE gq_prtsummaryline set returnedqty = 0, returnableqty = " + poslreceivedqty + " where id = " + prtslid);

                // 处理采购订单明细行信息
                //dealPODetail(prtid, prtslid);
                dealPODetail(prtid, prtslid, ppslid);
            }
        }
        try {
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_posline where ponum='" + ponum + "'");
            if (CollectionUtils.isNotEmpty(bySql1)){
                for (int i=0;i<bySql1.size();i++){
                    Map<String, Object> map = bySql1.get(i);
                    String receivedqty1 = MapUtils.getString(map, "receivedqty");
                    String unitcost1 = MapUtils.getString(map, "unitcost");
                    BigDecimal bigDecimal1 = new BigDecimal(unitcost1);
                    BigDecimal bigDecimal2 = new BigDecimal(receivedqty1);
                    BigDecimal paidamt = new BigDecimal("0");
                    paidamt = bigDecimal1.multiply(bigDecimal2);
                    //paidamt:累计已开票金额  //unpaidamt:待开票金额
                    decimal=decimal.add(paidamt);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerService.updateBySql("update gq_po set unpaidamt ='"+decimal+"' where ponum = '"+ponum+"'");
    }
    //处理供应商台账返回数据问题
    public void dealReceiptPO11(Long prtid) throws Exception {
        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_prtdetailline where prtid ='" + prtid + "'");
        if (CollectionUtils.isNotEmpty(bySql)){
            for (int i=0;i<bySql.size();i++){
                Map<String, Object> map = bySql.get(i);
                String prlid = MapUtils.getString(map, "prlid");//采购申请id
                Float receiveqty = MapUtils.getFloat(map, "receiveqty");//入库数量
                String binnum = MapUtils.getString(map, "binnum");//货位
                String batchnum = MapUtils.getString(map, "batchnum");//批次
                String unitcost1 = MapUtils.getString(map, "unitcost");//单价
                BigDecimal unitcost = new BigDecimal(unitcost1);
                String subjectno = MapUtils.getString(map, "subjectno");//课题号
                String proid = MapUtils.getString(map, "proid");//课题号
                String taskid = MapUtils.getString(map, "taskid");//任务号
                String applyby = MapUtils.getString(map, "applyby");//需求人id
                String warehousedesc = MapUtils.getString(map, "warehousedesc");//库房名称
                String warehousenum = MapUtils.getString(map, "warehousenum");//库房编码
                handlerService.updateBySql("update gq_prline set binnum='"+binnum+"',batchnum='"+batchnum+"',warehousenum='"+warehousenum+"',warehousedesc='"+warehousedesc+"' where id='"+prlid+"'");
            }
        }
    }

    /**
     * 处理采购订单明细行信息
     *
     * @param prtid
     * @param prtslid
     */
    private void dealPODetail(Long prtid, Integer prtslid, Integer ppslid) {
        // 查询采购接收明细行信息
        String insresults = "合格";
        //原逻辑
        //List<Map<String, Object>> prtdlList = handlerService.findBySql("SELECT receiveqty,qualiquan, polid, id,arrquantity from gq_prtdetailline where insresults='" + insresults + "' and  prtid = " + prtid + " and ppslid = " + ppslid);
        List<Map<String, Object>> prtdlList = handlerService.findBySql("SELECT receiveqty,qualiquan, polid, id,arrquantity from gq_prtdetailline where insresults='" + insresults + "' and  prtid = " + prtid + " and prtslid = " + prtslid);

        if (CollectionUtils.isNotEmpty(prtdlList)) {
            for (Map<String, Object> prtdlMap : prtdlList) {
                Integer prtdlid = MapUtils.getInteger(prtdlMap, "id");
                Integer polid = MapUtils.getInteger(prtdlMap, "polid");
                Float prlorderqty = MapUtils.getFloat(prtdlMap, "qualiquan");//之前是以入库数更新采购订单里的数据，现在修改成合格数
                Float arrquantity = MapUtils.getFloat(prtdlMap, "arrquantity");
                // 查询采购订单行信息
                List<Map<String, Object>> polList = handlerService.findBySql("select receivedqty, orderqty, inspectqty,arrquantity from gq_poline where id = " + polid);
                //List<Map<String, Object>> polList = handlerService.findBySql("select receivedqty, orderqty, inspectqty from gq_poline where ppslid = " + ppslid);
                Map<String, Object> polMap = polList.get(0);
                Float polorderqty = MapUtils.getFloat(polMap, "orderqty");// 采购数量
                Float polreceivedqty = MapUtils.getFloat(polMap, "receivedqty");// 接收数量
                Float polinspectqty = MapUtils.getFloat(polMap, "inspectqty");// 验收数量
                Float arrquantity1 = MapUtils.getFloat(polMap, "arrquantity");//到货数量
                // 计算数量
                polreceivedqty = polreceivedqty + prlorderqty;//总的接收数量（已接收+本次接收数量）
                polinspectqty = polinspectqty + prlorderqty;//总的验收数量（已验收+本次验收数量）
                Float poluninspectqty = polorderqty - polinspectqty;
                Float polunreceivedqty = polorderqty - polreceivedqty;//总的未接受数量（采购数量-总的接收数量）
                arrquantity1=arrquantity1-arrquantity;
                String receiptscomplete = "已接收完成";
                if (!polorderqty.equals(polreceivedqty)) {
                    receiptscomplete = "已完成部分接受";
                }

                // 更新采购订单行数据
                handlerService.updateBySql("UPDATE gq_poline set receiptscomplete='" + receiptscomplete
                        + "', inspectqty = " + polinspectqty + ", receivedqty =" + polreceivedqty
                        + ", uninspectqty =" + poluninspectqty + ", unreceivedqty =" + polunreceivedqty + ",arrquantity="+arrquantity1+" where id = " + polid);
                try {
                    //更新框架合同接收数和待接收数
                    setConInfo(polid,prlorderqty);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 更新采收接收行可退换数量
                handlerService.updateBySql("UPDATE gq_prtdetailline set returnedqty = 0, returnableqty = " + polreceivedqty + " where id = " + prtdlid);
            }
        }
    }
    /*
    * 根据采购订单行数据，更新框架合同中的已入库数和待入库数量
    *
    * */
    private void setConInfo(int id,float polreceivedqty){
        //查询子合同信息，然后再查询框架合同信息
        List<Map<String,Object>> list = handlerService.findBySql("select cconid,cconpid,itemnum from gq_poline where id = "+id);
        if(CollectionUtils.isNotEmpty(list)){
            //int conid=MapUtils.getIntValue(list.get(0),"conid");//子合同序号
           // int conpid = MapUtils.getIntValue(list.get(0),"conpid");//子合同主键id
            int cconid=MapUtils.getIntValue(list.get(0),"cconid");//框架合同序号
            int cconpid = MapUtils.getIntValue(list.get(0),"cconpid");//框架合同主键id

                List<Map<String,Object>> listss = handlerService.findBySql("select receivedqty ,id,unreceivedqty from gq_conpoline where conid="+cconid +" and conpid ="+cconpid +" and" +
                        " itemnum = '"+list.get(0).get("itemnum")+"'");
                if(com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(listss)){
                    float receivedqty=0;//框架合同中物质已接收
                    float unreceivedqty=0;
                    int ids = MapUtils.getIntValue(listss.get(0),"id");
                    if(ToolUtil.isNotEmpty(listss.get(0).get("receivedqty"))){
                        receivedqty = MapUtils.getIntValue(listss.get(0),"receivedqty");//已接收
                    }
                    if(ToolUtil.isNotEmpty(listss.get(0).get("unreceivedqty"))){
                        unreceivedqty = MapUtils.getIntValue(listss.get(0),"unreceivedqty");//待接收
                    }
                    receivedqty=receivedqty+polreceivedqty;
                    unreceivedqty = unreceivedqty -polreceivedqty;
                    handlerService.updateBySql("update gq_conpoline set receivedqty ="+receivedqty +",unreceivedqty = "+unreceivedqty+"  where id = "+ids);
                }



        }
    }

    /**
     * 根据采购退/换处理采购订单汇总行信息
     *
     * @param prtid
     */
    private void dealReturnExgPO(Long prtid) {
        //查询退货数量大于0的汇总行数据
        List<Map<String, Object>> prslList = handlerService.findBySql("SELECT returnqty, prtslid, poslid,ppslid,unitcost from gq_prtsummaryline where id = " + prtid + "");

        if (CollectionUtils.isNotEmpty(prslList)) {
            for (Map<String, Object> prslMap : prslList) {
                Float returnqty = MapUtils.getFloat(prslMap, "returnqty");// 退换数量
                //汇总行退换数量大于0时，才做下边的逻辑处理
                Integer poslid = MapUtils.getInteger(prslMap, "poslid");//采购订单汇总行id
                Integer prtslid = MapUtils.getInteger(prslMap, "prtslid");//
                Integer ppslid = MapUtils.getInteger(prslMap, "ppslid");//采购接收汇总行，跟采购接收行关联关系
                String unitcost = MapUtils.getString(prslMap, "unitcost");//单价
                /* 更新采购订单行拒收数量 */
                // 查询采购订单汇总行信息
                //rejectedqty:退货数量  orderqty:采购数量  unreceivedqty:未接收数量
                List<Map<String, Object>> poslList = handlerService.findBySql("select rejectedqty, orderqty,unreceivedqty,reamount from gq_posline where id = " + poslid);
                Map<String, Object> poslMap = poslList.get(0);
                Float poslrejectedqty = MapUtils.getFloat(poslMap, "rejectedqty");// 拒绝接收数量（等同于退货数）
                Float poslorderqty = MapUtils.getFloat(poslMap, "orderqty");// 采购数量
                Float unreceivedqty = MapUtils.getFloat(poslMap, "unreceivedqty");// 未接收数

                // 计算拒绝接收数量
                poslrejectedqty = poslrejectedqty + returnqty;//原退货数加上退货数
                Float poslunrejectedqty = poslorderqty - poslrejectedqty;
                unreceivedqty = unreceivedqty;//原未接收数减去退货数
                // 更新采购订单汇总行数据  更新内容：原退货数加上新退货数  未接受数量=原未接受数量减去退货数量
                //unrejectedqty:未拒绝数量  unreceivedqty:未接收数

                handlerService.updateBySql("UPDATE gq_posline set rejectedqty = " + poslrejectedqty + ", unrejectedqty = " + poslunrejectedqty + ",unreceivedqty = " + unreceivedqty + "  where id = " + poslid);
                List<Map<String, Object>> poslList1 = handlerService.findBySql("select rejectedqty,reamount from gq_posline where id = " + poslid);
                if(CollectionUtils.isNotEmpty(poslList1)){
                    Map<String, Object> map = poslList1.get(0);
                    String rejectedqty1 = MapUtils.getString(map, "rejectedqty");
                    String reamount = MapUtils.getString(map, "reamount");//退货金额
                    BigDecimal bigDecimal = new BigDecimal(rejectedqty1);
                    BigDecimal bigDecimal1 = new BigDecimal(unitcost);
                    BigDecimal bigDecimal2 = new BigDecimal(0);
                    if(ToolUtil.isNotEmpty(reamount)){
                        bigDecimal2 = new BigDecimal(reamount);
                    }
                    bigDecimal2=bigDecimal.multiply(bigDecimal1);
                    handlerService.updateBySql("UPDATE gq_posline set reamount="+bigDecimal2+" where id = " + poslid);
                }
                /*
                 * 未入库:针对已接收的采购接收行实际接收数量进行变更
                 * 已入库：暂不做处理
                 */
                // 更新采收接收汇总行退换数量
                // handlerService.updateBySql("UPDATE gq_prtdetailline set returnedqty = returnedqty + " + returnqty + ", returnableqty = receiveqty - returnedqty where id = " + prtslid);

                // 根据采购退/换处理采购订单明细行信息 备注：参数增加汇总行id，用户如果汇总行只有一行的退货，未接收数要置为0，保证下次不在被选择
                dealReturnExgPODetail(prtid,ppslid,poslid);


            }
        }
    }

    /**
     * 根据采购退/换处理采购订单明细行信息
     *
     * @param prtid
     * @param ppslid
     */
    private void dealReturnExgPODetail(Long prtid, Integer ppslid,Integer poslid) {
        // 查询采购接收明细行信息
        //List<Map<String, Object>> prtdlList = handlerService.findBySql("SELECT returnqty, id, polid from gq_prtdetailline where prtid = " + prtid + " and prtslid = " + prtslid);
        List<Map<String, Object>> prtdlList = handlerService.findBySql("SELECT receiveqty, id, polid,returnqty from gq_prtdetailline where prtslid = " + prtid + " and insresults='退货' and ppslid = "+ppslid);
            //入库数量:receiveqty  returnqty:退换数量
        if (CollectionUtils.isNotEmpty(prtdlList)) {
            //用户如果汇总行只有一行的退货，未接收数要置为0，确保下次不在被选择
//            if(prtdlList.size()==1){
//                handlerService.updateBySql("UPDATE gq_posline set  unreceivedqty = 0  where id = " + poslid);
//            }
            for (Map<String, Object> prtdMap : prtdlList) {
                Float returnqty = MapUtils.getFloat(prtdMap, "returnqty");//退换货数量
                Float qualiquan = MapUtils.getFloat(prtdMap, "qualiquan");//合格数量
                Integer polid = MapUtils.getInteger(prtdMap, "polid");//采购订单明细行id
                Integer prtdlid = MapUtils.getInteger(prtdMap, "id");

                /* 更新采购订单行拒收数量 */
                // 查询采购订单行信息
                List<Map<String, Object>> polList = handlerService.findBySql("select rejectedqty, orderqty,unreceivedqty from gq_poline where id = " + polid);
                Map<String, Object> polMap = polList.get(0);
                Float polrejectedqty = MapUtils.getFloat(polMap, "rejectedqty");// 拒绝接收数量
                Float polorderqty = MapUtils.getFloat(polMap, "orderqty");// 采购数量
                Float unreceivedqty = MapUtils.getFloat(polMap, "unreceivedqty");//未接收数量
                // 计算拒绝接收数量
                polrejectedqty = polrejectedqty + returnqty;
                Float polunrejectedqty = polorderqty - polrejectedqty;
//                unreceivedqty=unreceivedqty-qualiquan;


                // 更新采购订单行数据
                //采购订单行，未接收数置为0，退换数等于采购接收行里的退换货数量
                handlerService.updateBySql("UPDATE gq_poline set rejectedqty = " + polrejectedqty + ", unrejectedqty = " + polunrejectedqty + ",unreceivedqty =0 where id = " + polid);

                /*
                 * 未入库:针对已接收的采购接收行实际接收数量进行变更
                 * 已入库：暂不做处理
                 */
                // 1.更新采收接收行实际拒收数量
                // handlerService.updateBySql("UPDATE gq_prtdetailline set rejectqty = rejectqty + " + returnqty + ", returnableqty = receiveqty - returnedqty where id = " + prtdlid);
            }
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_poline where poslid='" + poslid + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                Float unreceivedqty1=(float)0;
                for (int i=0;i<bySql.size();i++){
                    Map<String, Object> map = bySql.get(i);
                    Float unreceivedqty = MapUtils.getFloat(map,"unreceivedqty");
                    unreceivedqty1=unreceivedqty1+unreceivedqty;
                }
                if (unreceivedqty1==0f){
                    handlerService.updateBySql("update gq_posline set unreceivedqty=0 where id='"+poslid+"'");
                }
            }
        }

    }

    /*
     *计算供应商到货率和合格率
     * */
    public void calculationPrPa(Long id) {

        List<Map<String, Object>> prtslList = handlerService.findBySql("SELECT ponum  from gq_purchasereceipt where id = " + id);

        if (CollectionUtils.isNotEmpty(prtslList)) {
            List<Map<String, Object>> poList = handlerService.findBySql("SELECT suppliernum  from gq_po where ponum = '" + prtslList.get(0).get("ponum") + "'");

            if (CollectionUtils.isNotEmpty(poList)) {
                //拿到供应商编号，对供应商的到货率和合格率进行重新计算
                String sql = "select zd.suppliernum,zd.suppliername,ROUND((zd.jishi/zd.zong*100))as jishis,\n" +
                        "(select hege from (select o.suppliernum,o.suppliername ,ROUND((sum(qualiquan)/sum(qualquantity)*100))as hege from gq_prtsummaryline e\n" +
                        "left JOIN gq_po o on e.poid = o.id\n" +
                        "GROUP BY o.suppliernum,o.suppliername) as hege where hege.suppliernum = zd.suppliernum) as hege\n" +
                        "\n" +
                        " from (\n" +
                        "SELECT\n" +
                        "\tod.suppliernum,\n" +
                        "\tod.suppliername,\n" +
                        "\tod.zong,\n" +
                        "IF (od.jishi IS NULL, 0, t.od.jishi) AS jishi\n" +
                        "FROM\n" +
                        "\t(\n" +
                        "\t\tselect a.suppliernum,a.suppliername,count(*)as zong,(\n" +
                        "select ab.jishi from (select a.suppliernum,a.suppliername,count(*) as jishi from \n" +
                        "(select suppliernum,suppliername from gq_prtdetailline e \n" +
                        "left join gq_purchasereceipt t on e.prtid = t.id \n" +
                        "left join gq_po p on t.ponum = p.ponum\n" +
                        "where t.arrivalate <= p.requireddate) as a\n" +
                        "group by a.suppliernum ,a.suppliername) ab where ab.suppliernum=a.suppliernum\n" +
                        ")as jishi\n" +
                        "\n" +
                        " from \n" +
                        "(select suppliernum,suppliername from gq_prtdetailline e \n" +
                        "left join gq_purchasereceipt t on e.prtid = t.id \n" +
                        "left join gq_po p on t.ponum = p.ponum\n" +
                        "where 1=1 ) as a\n" +
                        "group by a.suppliernum ,a.suppliername\n" +
                        "\n" +
                        "\t) AS od) as zd where zd.suppliername is not null and zd.suppliernum='" + poList.get(0).get("suppliernum") + "'";

                System.out.println("供应商评价sql=====" + sql);
                List<Map<String, Object>> list = null;
                try {
                    list = handlerService.findBySql(sql);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (CollectionUtils.isNotEmpty(list)) {
                    String upd = "update gq_account set promptness='" + list.get(0).get("jishis") + "',passrate='" + list.get(0).get("hege") + "' where supplierno ='" + poList.get(0).get("suppliernum") + "'";
                    System.out.println("修改合格率和及时率sql==" + upd);
                    handlerService.updateBySql(upd);
                }

            }
        }
    }
//返回采购申请入库数量
    public void repurchquest(Long id)throws Exception{
        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_purchasereceipt where id = " + id + "");
        if (CollectionUtils.isNotEmpty(bySql)){

            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_prtdetailline where prtid=" + id + "");
            if (CollectionUtils.isNotEmpty(bySql1)){
               for (int i=0;i<bySql1.size();i++){
                   Map<String, Object> map = bySql1.get(i);
                   String prlid = MapUtils.getString(map, "prlid");
                   Float receiveqty = MapUtils.getFloat(map, "receiveqty");
                   List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_prline where id='" + prlid + "'");
                   if (CollectionUtils.isNotEmpty(bySql2)){
                       Float receiveqty1 = MapUtils.getFloat(bySql2.get(0), "receiveqty");
                       receiveqty1=receiveqty1+receiveqty;
                       handlerService.updateBySql("update gq_prline set receiveqty="+receiveqty1+" where id='"+prlid+"'");
                   }
               }
            }
        }
    }
    private void appwarehousing(Long puid) throws Exception {
        List<Map<String, Object>> prtslList = handlerService.findBySql("SELECT *  from gq_purchasereceipt where id = " + puid + " and waremethod ='手工入库'");
        if (CollectionUtils.isNotEmpty(prtslList)) {
            HashMap<String, String> hashMap2 = new HashMap<>();
            Map<String, Object> result = new HashMap<>();
            String code = "9999";
            String message = "";
            String idt = "";
            String receiptnum = "";
            String insresults = "合格";
            String sql = "select * from gq_prtdetailline where insresults='" + insresults + "' and  prtid =" + puid;
            List<Map<String, Object>> list = handlerService.findBySql(sql);
            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> map : list) {
                    Integer prtdetaillineId = MapUtils.getInteger(map, "id");//采购接收明细行id
                    Integer numbers = 0;
                    String prlid = MapUtils.getString(map, "prlid");//采购申请行id
                    String pplid = MapUtils.getString(map, "pplid");//采购计划行id
                    String polid = MapUtils.getString(map, "polid");//采购订单明细行id
                    String storenum = MapUtils.getString(map, "warehousenum");//库房
                    String binnum = MapUtils.getString(map, "binnum");//货位
                    String manbanumber = MapUtils.getString(map, "manbanumber");//厂商批次号
                    String facnumber = MapUtils.getString(map, "facnumber");//厂商编号
                    String createuser = MapUtils.getString(map, "createuser");
                    String deptcode = MapUtils.getString(map, "deptcode");
                    String unit = MapUtils.getString(map, "orderunit");//计量单位
                    receiptnum = MapUtils.getString(prtslList.get(0), "receiptnum");//采购接收编号
                    log.info("receiptnum+++++++++++++++++++++++++++++++++++++" + receiptnum);
                    String itemnum = MapUtils.getString(map, "itemnum");//物料编码
                    String itemdesc = MapUtils.getString(map, "itemdesc");//物料名称
                    String batchnum = MapUtils.getString(map, "batchnum");//批次号
                    String subjectno = MapUtils.getString(map, "subjectno");//课题号
                    String taskid1 = MapUtils.getString(map, "taskid");//任务编号
                    String pronum = MapUtils.getString(map, "pronum");//项目编号
                    String occupnot = MapUtils.getString(map, "occupnot");//是否本人占用
                    String applyby = MapUtils.getString(map, "applyby");//占用人
                    String aactualdate = MapUtils.getString(map, "aactualdate");//出厂日期
                    //String insresults = MapUtils.getString(map, "insresults");//检验结果
                    //修改采购计划完事，往入库记录里查数据数量为0的问题
                    Integer receiveqty = MapUtils.getInteger(map, "receiveqty");//入库数量
                    if (receiveqty != null) {
                        numbers = receiveqty;
                    }
                    String where = "";
                    StringBuffer wheres = new StringBuffer();
                    if (batchnum != null && !"".equals(batchnum) && !"".equals(binnum)) {
                        //where = " and binnum = '"+binnum+"' and batchnum ='" + batchnum + "'";
                        wheres.append(" and binnum = '" + binnum + "' and batchnum ='" + batchnum + "'");
                    }
                    if (!"".equals(subjectno) && subjectno != null) {
                        wheres.append(" and  subjectno = '" + subjectno + "'");
                    }
                    if (!"".equals(pronum) && pronum != null) {
                        wheres.append(" and  pronum = '" + pronum + "'");
                    }
                    if (!"".equals(taskid1) && taskid1 != null) {
                        wheres.append(" and  taskid = '" + taskid1 + "'");
                    }
                    where = wheres.toString();


//                    List<Map<String, Object>> bySql = handlerService.findBySql("select itemnum from gq_prtdetailline where prtid ='" + puid + "'");
//                    for (Map<String, Object> map3 : bySql) {
//                        String sonitemnum = MapUtils.getString(map3, "itemnum");
//                        String msg;  //receiptnum
//                        if (itemnum.equals(sonitemnum)) {
//                            handlerService.updateBySql("update gq_prtdetailline set warehousenum ='" + storenum + "',binnum ='" + shelfnum + "' where prtid ='" + puid + "' and itemnum ='" + itemnum + "'");
//                            msg = ("采购接收号:" + receiptnum + ",\n物料编码:" + itemnum + ",\n批次号:" + batchnum + ",\n更新成功");
//                            hashMap2.put("storenum", storenum);
//                            hashMap2.put("shelfnum", shelfnum);
//                            hashMap2.put("itemnum", itemnum);
//                            hashMap2.put("batchnum", batchnum);
//                            hashMap2.put("receiptnum", receiptnum);
//                        } else {
//                            msg = ("采购接收号:" + receiptnum + ",\n物料编码:" + itemnum + ",\n批次号:" + batchnum + ",\n更新失败");
//                        }
//                        message = message + msg + "\n";
//                    }
                    //1.根据itemnum和storenum判断库存台账是否有此条数据(库存台账表：gq_inventory)
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_inventory where itemnum ='" + itemnum + "' and storenum ='" + storenum + "'");
                    if (bySql1 == null || bySql1.size() == 0) {
                        //库存台账不存在此条数据,新建库存台账
                        Map<String, Object> map1 = new HashMap<>();
                        map.put("itemnum", itemnum);
                        map.put("itemdesc", itemdesc);
                        //库房表：gq_store 库房编码:storenum  库房描述:storedesc
                        List<Map<String, Object>> bySql2 = handlerService.findBySql("select storedesc from gq_store where storenum ='" + storenum + "'");
                        String storedesc = MapUtils.getString(bySql2.get(0), "storedesc");
                        map.put("storenum", storenum);
                        map.put("storedesc", storedesc);
                        BigInteger id = (BigInteger) handlerService.insert("gq_inventory", map);

                        //List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_prtdetailline where prtid ='" + puid + "' and itemnum ='" + itemnum + "' and warehousenum ='" + storenum + "' "+where);
                        List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_prtdetailline where id =" + prtdetaillineId);

                        if (bySql3 != null && bySql3.size() > 0) {
                            for (Map<String, Object> map3 : bySql3) {
                                String itemtype = MapUtils.getString(map3, "itemtype");
                                map.put("itemtype", itemtype);
                                String outunit = MapUtils.getString(map3, "outunit");
                                map.put("orderunit", outunit);
                                map.put("outunit", outunit);
                                String model = MapUtils.getString(map3, "model");
                                map.put("model", model);
                                String spemodel = MapUtils.getString(map3, "spemodel");
                                map.put("spemodel", spemodel);
                                String manufacturer = MapUtils.getString(map3, "manufacturer");
                                map.put("manufacturer", manufacturer);
                                map.put("id", id);
                                List<Map<String, Object>> bySql4 = handlerService.findBySql("select * from gq_item where itemnum ='" + itemnum + "' limit 1");
                                map.put("orderunit", MapUtils.getString(bySql4.get(0), "outunit"));
                                map.put("outunit", MapUtils.getString(bySql4.get(0), "outunit"));
                                map.put("packagform", MapUtils.getString(bySql4.get(0), "packform"));
                                map.put("moneylife", MapUtils.getString(bySql4.get(0), "lifemoney"));
                                map.put("quagrade", MapUtils.getString(bySql4.get(0), "qualitygrade"));
                                map.put("maintechindicat", MapUtils.getString(bySql4.get(0), "maintechtors"));
                                handlerService.update("gq_inventory", map);
                                //新建库存台账 成本子表
                                Map<String, Object> map4 = new HashMap<>();
                                String proid = MapUtils.getString(map3, "proid");
                                map4.put("proid", proid);
                                String taskid = MapUtils.getString(map3, "taskid");
                                map4.put("taskid", taskid);
                                //String subjectno = MapUtils.getString(map3, "subjectno");
                                map4.put("subjectno", subjectno);
                                map4.put("createuser",createuser);
                                map4.put("deptcode",deptcode);
                                String unitcost = MapUtils.getString(map3, "unitcost");
                                // float unitcost = MapUtils.getFloat(map3, "unitcost");
                                BigDecimal bigDecimal1 = new BigDecimal(unitcost);
                                map4.put("stdcost", bigDecimal1);
                                map4.put("avgcost", bigDecimal1);
                                String reamount = MapUtils.getString(map3, "reamount");
                                //float reamount = MapUtils.getFloat(map3, "reamount");
                                BigDecimal bigDecimal2 = new BigDecimal(0);
                                if(ToolUtil.isNotEmpty(reamount)){
                                    bigDecimal2 = new BigDecimal(reamount);
                                }
                                map4.put("lastcost", bigDecimal2);
                                map4.put("itemnum", itemnum);
                                map4.put("itemdesc", itemdesc);
                                map4.put("storenum", storenum);
                                map4.put("batchnum", batchnum);
                                try {
                                    handlerService.insert("gq_invcost", map4);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                //新建库存台账 余量子表
                                Map<String, Object> map5 = new HashMap<>();
                                map5.put("proid", proid);
                                map5.put("taskid", taskid);
                                map5.put("subjectno", subjectno);
//                                numbers = MapUtils.getInteger(map3, "receiveqty");
                                map5.put("curbal", numbers);
                                String expirydate = MapUtils.getString(map3, "expirydate");
                                if(StringUtils.isNotBlank(expirydate)){
                                    map5.put("enddate", expirydate);
                                    //根据失效日期和当前日期计算出失效天数
                                    int enddays = handlerExpirationDays(expirydate);
                                    map5.put("enddays",enddays);
                                }

                                map5.put("createuser",createuser);
                                map5.put("deptcode",deptcode);
                                map5.put("unitcost", bigDecimal1);
                                map5.put("itemnum", itemnum);
                                map5.put("itemdesc", itemdesc);
                                String orderunit = MapUtils.getString(map3, "orderunit");
                                map5.put("orderunit", orderunit);
                                map5.put("storenum", storenum);
                                map5.put("batchnum", batchnum);
                                map5.put("facnumber",facnumber);
                                map5.put("manbanumber",manbanumber);
                                String startdate =  DateUtiles.getYmdhms(new Date());
                                map5.put("startdate",startdate);//入库时间
                                map5.put("occupnot",occupnot);//是否是本人占用
                                map5.put("aactualdate",aactualdate);//出厂日期
                                if("否".equals(occupnot)){
                                    //当是否专用为否时，增加可用余量不增加占用余量
                                    map5.put("avblbalance", numbers);

                                }else if ("是".equals(occupnot)){
                                    map5.put("reservedqty", numbers);
                                    map5.put("applyby", applyby);
                                    //当是否专用为是时，增加占用余量不增加可用余量
                                    List<Map<String, Object>> sys_setting = handlerService.findBySql("select field8 from sys_setting");//系统设置控制开关
                                    if (CollectionUtils.isNotEmpty(sys_setting)){
                                        String field8 = MapUtils.getString(sys_setting.get(0), "field8");
                                        if (field8.equals("1")) {
                                            map5.put("numusage", numbers);
                                        }else {
                                            map5.put("avblbalance", numbers);
                                        }
                                    }
                                }
                                map5.put("binnum", MapUtils.getString(map3, "binnum"));
                                map5.put("receiptnum", receiptnum);
                                handlerService.insert("gq_invbalances", map5);
                                //当是否专用为是时，增加占用余量不增加可用余量
                                List<Map<String, Object>> sys_setting = handlerService.findBySql("select field8 from sys_setting");//系统设置控制开关
                                if (CollectionUtils.isNotEmpty(sys_setting)){
                                    String field8 = MapUtils.getString(sys_setting.get(0), "field8");
                                    if (field8.equals("1")){
                                        List<Map<String, Object>> bySql = handlerService.findBySql("select id,occupnot from gq_invbalances where batchnum='" + batchnum + "'");
                                        if (CollectionUtils.isNotEmpty(bySql)){
                                            String id1 = MapUtils.getString(bySql.get(0), "id");
                                            String occupnot1 = MapUtils.getString(bySql.get(0), "occupnot");
                                            if ("是".equals(occupnot1)){
                                                HashMap<String, Object> hashMap = new HashMap<>();
                                                hashMap.put("numusage",numbers);
                                                hashMap.put("applyby",applyby);
                                                hashMap.put("invbalancesid",id1);
                                                hashMap.put("prid",prlid);
                                                handlerService.insert("gq_occurecords",hashMap);
                                            }
                                        }
//
                                    }
                                }
                            }
                        }
                    } else {


                        //获取接收子表数量,添加到库存台账 余量表
                        //List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_prtdetailline where  prtid ='" + puid + "' and itemnum ='" + itemnum + "' and warehousenum ='" + storenum + "' "+where);
                        List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_prtdetailline where  id =" + prtdetaillineId);
                        String orderunit = MapUtils.getString(bySql3.get(0), "orderunit");
                        numbers = MapUtils.getInteger(bySql3.get(0), "receiveqty");
                        List<Map<String, Object>> bySq4 = handlerService.findBySql("select * from gq_invbalances where itemnum ='" + itemnum + "' and storenum ='" + storenum + "' " + where);
                        if (bySq4 != null && bySq4.size() > 0) {
                            Integer avblbalance = MapUtils.getInteger(bySq4.get(0), "avblbalance");
                            Integer curbal = MapUtils.getInteger(bySq4.get(0), "curbal");
                            avblbalance = avblbalance + numbers;
                            curbal = curbal + numbers;
                            System.out.println("余量数据curbal====================" + curbal + "==========avblbalance=========" + avblbalance);
                            handlerService.updateBySql("update gq_invbalances set avblbalance =" + avblbalance + ",curbal =" + curbal + " where itemnum ='" + itemnum + "' and storenum ='" + storenum + "' " + where);
                            //新建成本表
                            //handlerService.update("insert into gq_invcost (proid,taskid,batchnum,stdcost,avgcost,lastcost,storenum) values ('"++"','"++"','"++"','"++"','"++"','"++"','"++"','"++"')");
                        } else {
                            //新建库存台账 余量子表
                            Map<String, Object> map5 = new HashMap<>();
                            map5.put("proid", bySql3.get(0).get("proid"));
                            map5.put("taskid", bySql3.get(0).get("taskid"));
                            map5.put("subjectno", bySql3.get(0).get("subjectno"));
//                                numbers = MapUtils.getInteger(map3, "receiveqty");

                            map5.put("curbal", numbers);
                            String expirydate = MapUtils.getString(bySql3.get(0), "expirydate");
                            map5.put("enddate", expirydate);
                            String unitcost = MapUtils.getString(bySql3.get(0), "unitcost");
                            // float unitcost = MapUtils.getFloat(map3, "unitcost");
                            BigDecimal bigDecimal1 = new BigDecimal(unitcost);
                            map5.put("unitcost", bigDecimal1);
                            map5.put("itemnum", itemnum);
                            map5.put("itemdesc", itemdesc);
                            map5.put("storenum", storenum);
                            map5.put("orderunit",orderunit);
                            map5.put("batchnum", batchnum);
                            map5.put("manbanumber",manbanumber);
                            map5.put("facnumber",facnumber);
                            map5.put("receiptnum", receiptnum);
                            map5.put("binnum", MapUtils.getString(bySql3.get(0), "binnum"));
                            String startdate =  DateUtiles.getYmdhms(new Date());
                            map5.put("startdate",startdate);//入库时间
                            map5.put("occupnot",occupnot);//是否是本人占用
//                            if ("是".equals(occupnot)) {
//                                //可用余量为0；预留数量等于入库数量
//                               // map5.put("avblbalance", numbers);
//                                map5.put("reservedqty", numbers);
//                                map5.put("applyby", applyby);
//                            }else {
//
//                            }
                            if("否".equals(occupnot)){
                                //当是否专用为否时，增加可用余量不增加占用余量
                                map5.put("avblbalance", numbers);
                            }else{
                                map5.put("reservedqty", numbers);
                                map5.put("applyby", applyby);
                                //当是否专用为是时，增加占用余量不增加可用余量
                                List<Map<String, Object>> sys_setting = handlerService.findBySql("select field8 from sys_setting");//系统设置控制开关
                                if (CollectionUtils.isNotEmpty(sys_setting)){
                                    String field8 = MapUtils.getString(sys_setting.get(0), "field8");
                                    if (field8.equals("1")){
                                        map5.put("numusage",numbers);
//                                        List<Map<String,String>> maps= new ArrayList<>();
//                                        String floatString1 = String.valueOf(numbers);
//                                        HashMap<String, String> hashMap1 = new HashMap<>();
//                                        hashMap1.put(applyby,floatString1);
//                                        maps.add(hashMap1);
//                                        StringBuilder stringBuilder = new StringBuilder();
//                                        for (Map<String, String> hashMapList : maps) {
//                                            for (Map.Entry<String, String> entry : hashMapList.entrySet()) {
//                                                String key = entry.getKey();
//                                                Object value = entry.getValue();
//                                                stringBuilder.append(key).append(": ").append(value).append(", ");
//                                            }
//                                        }
//                                        String occurecordss = stringBuilder.toString();
//                                        map5.put("occurecords",occurecordss);
                                    }
                                }
                            }
                            map5.put("createuser",createuser);
                            map5.put("deptcode",deptcode);
                            map5.put("aactualdate",aactualdate);//出厂日期
                            handlerService.insert("gq_invbalances", map5);
                            //当是否专用为是时，增加占用余量不增加可用余量
                            List<Map<String, Object>> sys_setting = handlerService.findBySql("select field8 from sys_setting");//系统设置控制开关
                            if (CollectionUtils.isNotEmpty(sys_setting)) {
                                String field8 = MapUtils.getString(sys_setting.get(0), "field8");
                                if (field8.equals("1")) {
                                    List<Map<String, Object>> bySql = handlerService.findBySql("select id,occupnot from gq_invbalances where batchnum='" + batchnum + "'");
                                    if (CollectionUtils.isNotEmpty(bySql)) {
                                        String id1 = MapUtils.getString(bySql.get(0), "id");
                                        String occupnot1 = MapUtils.getString(bySql.get(0), "occupnot");
                                        if ("是".equals(occupnot1)) {
//                                                List<Map<String,String>> maps= new ArrayList<>();
//                                            String floatString1 = String.valueOf(numbers);
//                                            HashMap<String, String> hashMap1 = new HashMap<>();
//                                            hashMap1.put(applyby, floatString1);
//                                            maps.add(hashMap1);
//                                            StringBuilder stringBuilder = new StringBuilder();
//                                            for (Map<String, String> hashMapList : maps) {
//                                                for (Map.Entry<String, String> entry : hashMapList.entrySet()) {
//                                                    String key = entry.getKey();
//                                                    Object value = entry.getValue();
//                                                    stringBuilder.append(key).append(": ").append(value).append(", ");
//                                                }
//                                            }
//                                            String occurecordss = stringBuilder.toString();
//                                            map5.put("occurecords",occurecordss);
                                            HashMap<String, Object> hashMap = new HashMap<>();
                                            hashMap.put("numusage", numbers);
                                            hashMap.put("applyby", applyby);
                                            hashMap.put("invbalancesid", id1);
                                            hashMap.put("prid", prlid);
                                            handlerService.insert("gq_occurecords", hashMap);
                                        }
                                    }
//
                                }
                            }
                            Map<String, Object> map4 = new HashMap<>();
                            String proid = MapUtils.getString(bySql3.get(0), "proid");
                            map4.put("proid", proid);
                            String taskid = MapUtils.getString(bySql3.get(0), "taskid");
                            map4.put("taskid", taskid);
                            //String subjectno = MapUtils.getString(map3, "subjectno");
                            map4.put("subjectno", subjectno);

                            map4.put("stdcost", bigDecimal1);
                            map4.put("avgcost", bigDecimal1);
                            String reamount = MapUtils.getString(bySql3.get(0), "reamount");
                            //float reamount = MapUtils.getFloat(map3, "reamount");
                            BigDecimal bigDecimal2 = new BigDecimal(reamount);
                            if(ToolUtil.isNotEmpty(0)){
                                bigDecimal2 = new BigDecimal(reamount);
                            }
                            map4.put("lastcost", bigDecimal2);
                            map4.put("itemnum", itemnum);
                            map4.put("createuser",createuser);
                            map4.put("deptcode",deptcode);
                            map4.put("itemdesc", itemdesc);
                            map4.put("storenum", storenum);
                            map4.put("batchnum", batchnum);
                            handlerService.insert("gq_invcost", map4);
                        }
                    }

                    List<Map<String, Object>> bySql4 = handlerService.findBySql("select avblbalance,curbal,reservedqty,numusage from gq_invbalances where itemnum ='" + itemnum + "' and storenum ='" + storenum + "'");
                    Integer curbaltotal = 0;
                    Integer avblbalancetotal = 0;
                    Integer reservedqtytotal = 0;
                    Integer numusagetotal =0;//占用量总量
                    for (Map<String, Object> map3 : bySql4) {
                        Integer avblbalance = MapUtils.getInteger(map3, "avblbalance");
                        Integer curbal = MapUtils.getInteger(map3, "curbal");
                        Integer reservedqty = MapUtils.getInteger(map3, "reservedqty");
                        Integer numusage =MapUtils.getInteger(map3,"numusage");//占用量
                        curbaltotal = curbaltotal + curbal;
                        avblbalancetotal = avblbalancetotal + avblbalance;
                        reservedqtytotal = reservedqtytotal + reservedqty;
                        numusagetotal=numusagetotal+numusage;//计算总占用量
                    }
                    handlerService.updateBySql("update gq_inventory set curbaltotal =" + curbaltotal + ",avblbalance =" + avblbalancetotal + ",reservedqty = "+reservedqtytotal+",numusage="+numusagetotal+" where itemnum ='" + itemnum + "' and storenum ='" + storenum + "'");
                    //新建入库记录
                    Map<String, Object> map1 = new HashMap<>();
//                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select instonum from gq_matusetrans where type in('接收','退回') order by instonum desc limit 1");
//                    Integer instonum = MapUtils.getInteger(bySql2.get(0), "instonum");
//                    instonum++;
                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select instonum from gq_matusetrans where type in('接收','退回') and instonum like '%CDFI%' order by instonum desc limit 1");
                    String instonum = "";
                    if (bySql2.get(0) != null) {
                        instonum = MapUtils.getString(bySql2.get(0), "instonum");
                        int instonumin = Integer.valueOf(instonum.substring(instonum.length() - 8));
                        instonumin++;
                        instonum = "CDFI" + instonumin;
                    } else {
                        instonum = "CDFI10000001";
                    }

//                    Map<String, Object> maMap = new HashMap<>();
//                    handlerService.addBizNum("inventoryApp", "gq_matusetrans", maMap);
//                    String instonum = (String) maMap.get("instonum");//MapUtils.getInteger(bySql2.get(0), "instonum");
                    System.out.println("交易编号==================instonum=============" + instonum);
                    map1.put("instonum", instonum);
                    map1.put("instodesc", receiptnum + "接收入库");
                    map1.put("itemnum", itemnum);
                    map1.put("itemdesc", itemdesc);
                    map1.put("storenum", storenum);
                    List<Map<String, Object>> bySql3 = handlerService.findBySql("select storedesc from gq_store where storenum ='" + storenum + "'");
                    String storedesc = MapUtils.getString(bySql3.get(0), "storedesc");
                    //List<Map<String, Object>> bySql6 = handlerService.findBySql("select * from gq_prtdetailline where prtid ='" + puid + "' and itemnum ='" + itemnum + "' and warehousenum ='" + storenum + "' "+where);
                    List<Map<String, Object>> bySql6 = handlerService.findBySql("select * from gq_prtdetailline where id =" + prtdetaillineId);
                    String prtid = MapUtils.getString(bySql6.get(0), "prtid");

                    String unitcost = MapUtils.getString(bySql6.get(0), "unitcost");
                    BigDecimal bigDecimal1 = new BigDecimal(unitcost);
                    //Float unitcost = MapUtils.getFloat(bySql6.get(0), "unitcost");
                    String reamount = MapUtils.getString(bySql6.get(0), "reamount");
                    BigDecimal bigDecimal2 = new BigDecimal(0);
                    if(ToolUtil.isNotEmpty(reamount)){
                        bigDecimal2 = new BigDecimal(reamount);
                    }
                    // Float reamount = MapUtils.getFloat(bySql6.get(0), "reamount");
                    String proid = MapUtils.getString(bySql6.get(0), "proid");
                    String taskid = MapUtils.getString(bySql6.get(0), "taskid");
                    map1.put("binnum", binnum);
                    map1.put("prtdetaillineid",prtdetaillineId);//采购接收明细行id
                    map1.put("prlid",prlid);//采购申请行id
                    map1.put("polid",polid);//采购订单明细行id
                    map1.put("pplid",pplid);//采购计划明细行id
                    map1.put("unit", unit);
                    map1.put("storedesc", storedesc);
                    map1.put("createuser",createuser);
                    map1.put("deptcode",deptcode);
                    map1.put("facnumber",facnumber);
                    map1.put("unitcost", bigDecimal1);
                    map1.put("linecost", bigDecimal2);
                    map1.put("receiptnum", receiptnum);
                    map1.put("proid", proid);
                    map1.put("taskid", taskid);
                    map1.put("prtid", prtid);
                    map1.put("quantity", numbers);
                    map1.put("type", "接收");
                    map1.put("lotnum", batchnum);
                    map1.put("subjectno", subjectno);
                    //List<Map<String, Object>> bySql5 = handlerService.findBySql("select ponum from gq_purchasereceipt where prtid ='" + puid + "'");
                    map1.put("ponum", MapUtils.getString(prtslList.get(0), "ponum"));
                    try {
                        handlerService.insert("gq_matusetrans", map1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            }
        }

    }

    //根据失效日期距当前日期计算出失效天数
    private int handlerExpirationDays(String expirydate) {
        Date expirydate1 = DateUtils.getDate(expirydate);
        Date currentDate = DateUtils.getCurrentDate();
        int day = DateUtils.daysBetween(currentDate,expirydate1);
        if(day < 0){
            day = 0;
        }
        return day;
    }
}
